Skip to content

Commit 478ae20

Browse files
raof01azl397985856
authored andcommitted
feat: #1031: add concise C++ implementation (#164)
1 parent 88823f9 commit 478ae20

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

problems/1031.maximum-sum-of-two-non-overlapping-subarrays.md

+20
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,23 @@ class Solution:
104104

105105
1. 代码中, 求解了4个动态规划数组来求解最终值, 有没有可能只用两个数组来求解该题, 可以的话, 需要保留的又是哪两个数组?
106106
2. 代码中, 求解的4动态规划数组的顺序能否改变, 哪些能改, 哪些不能改?
107+
108+
如果采用前缀和数组的话,可以只使用O(n)的空间来存储前缀和,O(1)的动态规划状态空间来完成。C++代码如下:
109+
```C++
110+
class Solution {
111+
public:
112+
int maxSumTwoNoOverlap(vector<int>& A, int L, int M) {
113+
auto tmp = vector<int>{A[0]};
114+
for (auto i = 1; i < A.size(); ++i) {
115+
tmp.push_back(A[i] + tmp[i - 1]);
116+
}
117+
auto res = tmp[L + M - 1], lMax = tmp[L - 1], mMax = tmp[M - 1];
118+
for (auto i = L + M; i < tmp.size(); ++i) {
119+
lMax = max(lMax, tmp[i - M] - tmp[i - M - L]);
120+
mMax = max(mMax, tmp[i - L] - tmp[i - L - M]);
121+
res = max(res, max(lMax + tmp[i] - tmp[i - M], mMax + tmp[i] - tmp[i - L]));
122+
}
123+
return res;
124+
}
125+
};
126+
```

0 commit comments

Comments
 (0)