-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Maximum Sum of Distinct Subarrays With Length K
- Loading branch information
1 parent
8360c23
commit 342ea3c
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
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
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; | ||
} | ||
}; |