forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtle.cpp
More file actions
23 lines (23 loc) · 665 Bytes
/
Copy pathtle.cpp
File metadata and controls
23 lines (23 loc) · 665 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// OJ: https://leetcode.com/problems/constrained-subsequence-sum/
// Author: github.com/lzl124631x
// Time: O(NK)
// Space: O(N)
class Solution {
public:
int constrainedSubsetSum(vector<int>& A, int k) {
int maxVal = *max_element(begin(A), end(A));
if (maxVal <= 0) return maxVal;
int N = A.size(), ans = 0;
vector<int> dp(N);
for (int i = 0; i < N; ++i) {
int mx = 0;
for (int j = 1; j <= k; ++j) {
if (i - j < 0) break;
mx = max(mx, dp[i - j]);
}
dp[i] = mx + A[i];
ans = max(ans, dp[i]);
}
return ans;
}
};