<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return the maximum sum of a <strong>non-empty</strong> subsequence of that array such that for every two <strong>consecutive</strong> integers in the subsequence, <code>nums[i]</code> and <code>nums[j]</code>, where <code>i &lt; j</code>, the condition <code>j - i &lt;= k</code> is satisfied.</p>

<p>A <em>subsequence</em> of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [10,2,-10,5,20], k = 2
<strong>Output:</strong> 37
<b>Explanation:</b> The subsequence is [10, 2, 5, 20].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1,-2,-3], k = 1
<strong>Output:</strong> -1
<b>Explanation:</b> The subsequence must be non-empty, so we choose the largest number.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [10,-2,-10,-5,20], k = 2
<strong>Output:</strong> 23
<b>Explanation:</b> The subsequence is [10, -2, -5, 20].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    void update(int start, int end, int node, vector<int>& st, int value, int indx){
        if(start==end){
            st[node]=value;
            return;
        }
        int mid=(start+end)/2;
        if(indx<=mid){
            update(start, mid, 2*node+1, st, value, indx);
        }else{
            update(mid+1, end, 2*node+2, st, value, indx);
        }
        st[node]=max(st[2*node+1], st[2*node+2]);
        return;
    }
    int query(int start, int end, int l, int r, int node, vector<int>& st){
        if(l>end || r<start) return 0;
        if(start>=l && end<=r) return st[node];
        int mid=(start+end)/2;
        int q1=query(start, mid, l, r, 2*node+1, st);
        int q2=query(mid+1, end, l, r, 2*node+2, st);
        return max(q1, q2);
    }
    int constrainedSubsetSum(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> st;
        st.resize(4*n, INT_MIN);
        update(0, n-1, 0, st, nums[0], 0);
        int maxSum=nums[0];
        for(int i=1;i<n;i++){
           int currMax=query(0, n-1, max(i-k, 0), i-1, 0, st);
           maxSum=max(maxSum, currMax+nums[i]);
           update(0, n-1, 0, st, currMax+nums[i], i);
        }
        return maxSum;
    }
};
131887