Skip to content

Commit 9c0fcb7

Browse files
authored
Problem Difficulty Level: Hard
1 parent 5584315 commit 9c0fcb7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*-------------------------
2+
Time Complexity: O(n)
3+
Space Complexity: O(n)
4+
---------------------------*/
5+
6+
class Solution {
7+
public:
8+
int constrainedSubsetSum(vector<int>& nums, int k) {
9+
10+
int n = nums.size();
11+
int maxSum = nums[0];
12+
deque<pair<int,int>> dp;
13+
dp.push_back({0, nums[0]});
14+
15+
for(int i = 1; i < n; i++)
16+
{
17+
if(i - dp.front().first > k) dp.pop_front();
18+
19+
int current = nums[i];
20+
if(dp.front().second > 0) current += dp.front().second;
21+
maxSum = max(current, maxSum);
22+
23+
while(!dp.empty() && dp.back().second < current) dp.pop_back();
24+
dp.push_back({i, current});
25+
}
26+
27+
return maxSum;
28+
}
29+
};
30+
31+
/*
32+
Question Link: https://leetcode.com/problems/constrained-subsequence-sum/
33+
Author: M.R.Naganathan
34+
*/

0 commit comments

Comments
 (0)