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

// 兩個關鍵
    // 維持deque.front最大
    // 當deque.front為A[i-k]時, pop掉, 代表i-k~i之間都沒拿, dist為k (pefixSum更新A[i])
class Solution {
public:
    int constrainedSubsetSum(vector<int>& A, int k) {
        // given j-i<=k
        // q.front(): 最左的index, s.t. A[front]~A[i-1] 加總為正
        // q.back(): maxsum start from index q.back()
        deque<int> maxd;
        int res = INT_MIN;
        for (int i=0; i<A.size(); ++i) {
            // 枚舉
            if (!maxd.empty())
                A[i] += maxd.front();
            res = max(res, A[i]);

            while (!maxd.empty() && maxd.back() < A[i])
                maxd.pop_back();
            if (A[i] > 0)
                maxd.push_back(A[i]);

            // 維護 (deque.front()已是A[i-k], 就拔掉, 代表當前dist為k)
            if (!maxd.empty() && i>=k && A[i-k] == maxd.front())
                maxd.pop_front();

        }
        return res;
    }
};

// queue, k=2
// [10]
// [10, 8]
// [10, 8]
// []
118962