-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaximumSumSubArrayOfSizeK.cpp
More file actions
33 lines (29 loc) · 1001 Bytes
/
maximumSumSubArrayOfSizeK.cpp
File metadata and controls
33 lines (29 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// problem link: https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
long long ans = 0;
long long currentSum = 0;
int begin = 0;
int end = 0;
unordered_map<int, int> numToIndex;
while (end < nums.size()) {
int currNum = nums[end];
int lastOccurrence =
(numToIndex.count(currNum) ? numToIndex[currNum] : -1);
// if current window already has number or if window is too big,
// adjust window
while (begin <= lastOccurrence || end - begin + 1 > k) {
currentSum -= nums[begin];
begin++;
}
numToIndex[currNum] = end;
currentSum += nums[end];
if (end - begin + 1 == k) {
ans = max(ans, currentSum);
}
end++;
}
return ans;
}
};