Created
November 15, 2024 22:04
-
-
Save SuryaPratapK/a28632cda2e99d7337dd3fe5bae6f4d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
#define ll long long | |
public: | |
long long maximumSubarraySum(vector<int>& nums, int k) { | |
int n=nums.size(); | |
ll max_sum=0; | |
unordered_map<int,int> freq; | |
ll win_sum=0; | |
for(int i=0;i<n;++i){ | |
//Step-1: Include right element | |
freq[nums[i]]++; | |
win_sum += nums[i]; | |
//Step-2: Exclude left element | |
if(i>=k){ | |
win_sum -= nums[i-k]; | |
freq[nums[i-k]]--; | |
if(freq[nums[i-k]]==0) | |
freq.erase(nums[i-k]); | |
} | |
//Step-3: Maximize max_sum | |
if(i>=k-1 and freq.size()==k) | |
max_sum = max(max_sum,win_sum); | |
} | |
return max_sum; | |
} | |
}; | |
/* | |
//JAVA | |
import java.util.HashMap; | |
class Solution { | |
public long maximumSubarraySum(int[] nums, int k) { | |
int n = nums.length; | |
long maxSum = 0; | |
long winSum = 0; | |
HashMap<Integer, Integer> freq = new HashMap<>(); | |
for (int i = 0; i < n; ++i) { | |
// Step-1: Include right element | |
freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1); | |
winSum += nums[i]; | |
// Step-2: Exclude left element | |
if (i >= k) { | |
winSum -= nums[i - k]; | |
freq.put(nums[i - k], freq.get(nums[i - k]) - 1); | |
if (freq.get(nums[i - k]) == 0) { | |
freq.remove(nums[i - k]); | |
} | |
} | |
// Step-3: Maximize maxSum | |
if (i >= k - 1 && freq.size() == k) { | |
maxSum = Math.max(maxSum, winSum); | |
} | |
} | |
return maxSum; | |
} | |
} | |
#Python | |
from collections import defaultdict | |
class Solution: | |
def maximumSubarraySum(self, nums: list[int], k: int) -> int: | |
n = len(nums) | |
max_sum = 0 | |
win_sum = 0 | |
freq = defaultdict(int) | |
for i in range(n): | |
# Step-1: Include right element | |
freq[nums[i]] += 1 | |
win_sum += nums[i] | |
# Step-2: Exclude left element | |
if i >= k: | |
win_sum -= nums[i - k] | |
freq[nums[i - k]] -= 1 | |
if freq[nums[i - k]] == 0: | |
del freq[nums[i - k]] | |
# Step-3: Maximize max_sum | |
if i >= k - 1 and len(freq) == k: | |
max_sum = max(max_sum, win_sum) | |
return max_sum | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment