-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstrainedSubsequenceSum.cpp
49 lines (45 loc) · 1.37 KB
/
ConstrainedSubsequenceSum.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
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int constrainedSubsetSum(vector<int>& nums, int k) {
int n = nums.size();
vector<int> dp(n);
dp[0] = nums[0];
int i, j, l, ans = INT_MIN;
for (i = 0; i < n; i++) {
dp[i] = nums[i];
for (j = i - 1, l = k; j >= 0 && l > 0; --j, --l) {
dp[i] = max(dp[j] + nums[i], dp[i]);
}
ans = max(ans, dp[i]);
}
return ans;
}
// Using heap
int constrainedSubsetSum(vector<int>& nums, int k) {
int n = nums.size(), ans = nums[0];
vector<int> dp(n);
deque<int> kWindow;
for (int i = 0; i < n; i++) {
dp[i] = nums[i];
if (kWindow.size()) {
dp[i] += dp[kWindow.front()];
}
ans = max(ans, dp[i]);
if (kWindow.size() && (i - k + 1) > kWindow.front()) kWindow.pop_front();
while (kWindow.size() && dp[kWindow.back()] <= dp[i]) kWindow.pop_back();
if (dp[i] > 0)
kWindow.push_back(i);
}
return ans;
}
};
int main() {
int n, k;
cin >> n >> k;
vector<int> nums(n);
for (int i = 0; i < n; i++) cin >> nums[i];
cout << (new Solution())->constrainedSubsetSum(nums, k);
return 0;
}