# Constrained Subsequence Sum in C++

Suppose we have an array called nums and an integer k, we have to find the maximum sum of a non-empty subsequence of that array such that for every two consecutive numbers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is true.

As we know a subsequence of an array is obtained by deleting some number of elements from the array, leaving the remaining elements in their original order.

So, if the input is like [10,2,-9,5,19] and k = 2, then the output will be 36 as the subsequence is [10,2,5,19].

To solve this, we will follow these steps −

• ret := -inf

• Define an array dp and copy given array into it

• Define one deque dq

• insert v[0] at the begining of dq

• n := size of v

• ret := v[0]

• for initialize i := 1, when i < n, update (increase i by 1), do −

• if i > k and first element of dq is same as dp[i - k - 1], then

• delete front element from dq

• dp[i] := maximum of dp[i] and (if dq is empty, then dp[i] + 0, otherwise first element of dp + dq[i])

• while (not dq is empty and last element of dq < dp[i]), do −

• delete last element from dq

• insert dp[i] at the end of dq

• ret := maximum of ret and dp[i]

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 10;
class Solution {
public:
int constrainedSubsetSum(vector<int>& v, int k) {
int ret = -inf;
vector<int> dp(v.begin(), v.end());
deque<int> dq;
dq.push_front(v[0]);
int n = v.size();
ret = v[0];
for (int i = 1; i < n; i++) {
if (i > k && dq.front() == dp[i - k - 1])
dq.pop_front();
dp[i] = max(dp[i], dq.empty() ? dp[i] + 0 : dp[i] +
dq.front());
while (!dq.empty() && dq.back() < dp[i])
dq.pop_back();
dq.push_back(dp[i]);
ret = max(ret, dp[i]);
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {10,2,-9,5,19};
cout << (ob.constrainedSubsetSum(v, 2));
}

## Input

{10,2,-9,5,19}, 2

## Output

36

Advertisements