-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSubArrray.cpp
More file actions
33 lines (30 loc) · 1011 Bytes
/
maxSubArrray.cpp
File metadata and controls
33 lines (30 loc) · 1011 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
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
int n = nums.size();
unordered_set<int> elements;
long long current_sum = 0;
long long max_sum = 0;
int begin = 0;
for (int end = 0; end < n; end++) {
if (elements.find(nums[end]) == elements.end()) {
current_sum += nums[end];
elements.insert(nums[end]);
if (end - begin + 1 == k) {
max_sum = max(max_sum, current_sum);
current_sum -= nums[begin];
elements.erase(nums[begin]);
begin++;
}
} else {
while (nums[begin] != nums[end]) {
current_sum -= nums[begin];
elements.erase(nums[begin]);
begin++;
}
begin++;
}
}
return max_sum;
}
};