<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>

#define ll long long
class Solution {
    map<ll,ll> mp[100001];
    ll f(ll ind,ll prev,vector<int>& nums, int k){
        ll n=nums.size();
        if(ind==n){
            return 0;
        }
        if(mp[prev+1].find(ind)!=mp[prev+1].end()){
            return mp[prev+1][ind];
        }
        ll pick=-1e9;
        if(prev==-1 || ind-prev<=k){
            pick=nums[ind]+f(ind+1,ind,nums,k);
        }
        ll notpick=f(ind+1,prev,nums,k);
        return mp[prev+1][ind]= max(pick,notpick);
    }
public:
    int constrainedSubsetSum(vector<int>& nums, int k) {
        ll n=nums.size();
        // int maxi=-1e9;
        // for(auto it:nums){
        //     maxi=max(maxi,it);
        // }
        // if(maxi<0){
        //     return maxi;
        // }
        vector<ll> dp(n,0);
        dp[0]=nums[0];
        priority_queue<pair<ll,ll>> pq;
        pq.push({dp[0],0});
        ll ans=dp[0];
        for(int i=1;i<n;i++){
            dp[i]=nums[i];
            ll x=0;
            while(!pq.empty() && (i-pq.top().second)>k){
                pq.pop();
            }
            if(!pq.empty()){
                x=max(x,pq.top().first);
            }
            dp[i]+=x;
            pq.push({dp[i],i});
            ans=max(ans,dp[i]);
        }
        return ans;
        //return f(0,-1,nums,k);
    }
};
164787