Skip to content

Commit

Permalink
Create Maximum Sum of Distinct Subarrays With Length K
Browse files Browse the repository at this point in the history
  • Loading branch information
nidhiupman568 authored Nov 19, 2024
1 parent 8360c23 commit 342ea3c
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Maximum Sum of Distinct Subarrays With Length K
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
long long ans = 0, sum = 0;
unordered_map<int, int> mp;
int i = 0;
while(i < k && i < nums.size()){ // store first k elements in the map
mp[nums[i]]++;
sum += nums[i];
i++;
}
if(mp.size() == k) ans = sum; // if all distinct, then ans = sum
while(i < nums.size()){
mp[nums[i]]++;
mp[nums[i-k]]--;
if(mp[nums[i-k]] == 0) mp.erase(nums[i-k]);

sum += nums[i];
sum -= nums[i-k];
if(mp.size() == k) ans = max(ans, sum);
i++;
}
return ans;
}
};

0 comments on commit 342ea3c

Please sign in to comment.