forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-subarray-ii.cpp
44 lines (36 loc) · 1.17 KB
/
maximum-subarray-ii.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: An integer denotes the sum of max two non-overlapping subarrays
*/
int maxTwoSubArrays(vector<int> nums) {
int n = nums.size();
vector<int> max_LR(n);
vector<int> max_RL(n);
// Compute the max sum of subarray from left to right.
int max_LR_sum = INT_MIN, LR_sum = 0;
for (int i = 0; i < n; ++i) {
LR_sum += nums[i];
max_LR_sum = max(max_LR_sum, LR_sum);
max_LR[i] = max_LR_sum;
LR_sum = max(LR_sum, 0);
}
// Compute the max sum of subarray from right to left.
int max_RL_sum = INT_MIN, RL_sum = 0;
for (int i = n - 1; i >= 0; --i) {
RL_sum += nums[i];
max_RL_sum = max(max_RL_sum, RL_sum);
max_RL[i] = max_RL_sum;
RL_sum = max(RL_sum, 0);
}
// Compute the max sum of two non-overlapping subarrays.
int max_sum = INT_MIN;
for (int i = 0; i < n - 1; ++i) {
max_sum = max(max_sum, max_LR[i] + max_RL[i+1]);
}
return max_sum;
}
};