Skip to content

Commit

Permalink
feat: #1031: add concise C++ implementation (azl397985856#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
raof01 authored and azl397985856 committed Sep 4, 2019
1 parent 88823f9 commit 478ae20
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions problems/1031.maximum-sum-of-two-non-overlapping-subarrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,23 @@ class Solution:

1. 代码中, 求解了4个动态规划数组来求解最终值, 有没有可能只用两个数组来求解该题, 可以的话, 需要保留的又是哪两个数组?
2. 代码中, 求解的4动态规划数组的顺序能否改变, 哪些能改, 哪些不能改?

如果采用前缀和数组的话,可以只使用O(n)的空间来存储前缀和,O(1)的动态规划状态空间来完成。C++代码如下:
```C++
class Solution {
public:
int maxSumTwoNoOverlap(vector<int>& A, int L, int M) {
auto tmp = vector<int>{A[0]};
for (auto i = 1; i < A.size(); ++i) {
tmp.push_back(A[i] + tmp[i - 1]);
}
auto res = tmp[L + M - 1], lMax = tmp[L - 1], mMax = tmp[M - 1];
for (auto i = L + M; i < tmp.size(); ++i) {
lMax = max(lMax, tmp[i - M] - tmp[i - M - L]);
mMax = max(mMax, tmp[i - L] - tmp[i - L - M]);
res = max(res, max(lMax + tmp[i] - tmp[i - M], mMax + tmp[i] - tmp[i - L]));
}
return res;
}
};
```

0 comments on commit 478ae20

Please sign in to comment.