forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths2.cpp
More file actions
18 lines (18 loc) · 761 Bytes
/
s2.cpp
File metadata and controls
18 lines (18 loc) · 761 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// OJ: https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
// Ref: https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/278251/JavaC%2B%2BPython-O(N)Time-O(1)-Space
class Solution {
public:
int maxSumTwoNoOverlap(vector<int>& A, int L, int M) {
partial_sum(A.begin(), A.end(), A.begin());
int ans = A[L + M - 1], Lmax = A[L - 1], Mmax = A[M - 1];
for (int i = L + M; i < A.size(); ++i) {
Lmax = max(Lmax, A[i - M] - A[i - L - M]);
Mmax = max(Mmax, A[i - L] - A[i - L - M]);
ans = max(ans, max(Lmax + A[i] - A[i - M], Mmax + A[i] - A[i - L]));
}
return ans;
}
};