forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-sum-of-3-non-overlapping-subarrays.cpp
46 lines (42 loc) · 1.46 KB
/
maximum-sum-of-3-non-overlapping-subarrays.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
const auto n = nums.size();
vector<int> accu = {0};
for (const auto& num : nums) {
accu.emplace_back(accu.back() + num);
}
vector<int> left_pos(n);
for (int i = k, total = accu[k] - accu[0]; i < n; ++i) {
if (accu[i + 1] - accu[i + 1 - k] > total) {
left_pos[i] = i + 1 - k;
total = accu[i + 1] - accu[i + 1 - k];
} else {
left_pos[i] = left_pos[i - 1];
}
}
vector<int> right_pos(n, n - k);
for (int i = n - k - 1, total = accu[n] - accu[n - k]; i >= 0; --i) {
if (accu[i + k] - accu[i] > total) {
right_pos[i] = i;
total = accu[i + k] - accu[i];
} else {
right_pos[i] = right_pos[i + 1];
}
}
vector<int> result(3);
for (int i = k, max_sum = 0; i <= n - 2 * k; ++i) {
auto left = left_pos[i - 1], right = right_pos[i + k];
auto total = (accu[i + k] - accu[i]) +
(accu[left + k] - accu[left]) +
(accu[right + k] - accu[right]);
if (total > max_sum) {
max_sum = total;
result = {left, i, right};
}
}
return result;
}
};