<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>monotonic queue Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/monotonic-queue/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/monotonic-queue/</link>
	<description></description>
	<lastBuildDate>Sun, 20 Dec 2020 18:07:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>monotonic queue Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/monotonic-queue/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1696. Jump Game VI</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1696-jump-game-vi/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1696-jump-game-vi/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 20 Dec 2020 09:19:34 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[monotonic queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7827</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;and an integer&#160;k. You are initially standing at index&#160;0. In one move, you can jump at most&#160;k&#160;steps forward without going outside&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1696-jump-game-vi/">花花酱 LeetCode 1696. Jump Game VI</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1696. Jump Game VI - 刷题找工作 EP376" width="500" height="281" src="https://www.youtube.com/embed/M_PzYd59_kk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>You are initially standing at index&nbsp;<code>0</code>. In one move, you can jump at most&nbsp;<code>k</code>&nbsp;steps forward without going outside the boundaries of the array. That is, you can jump from index&nbsp;<code>i</code>&nbsp;to any index in the range&nbsp;<code>[i + 1, min(n - 1, i + k)]</code>&nbsp;<strong>inclusive</strong>.</p>



<p>You want to reach the last index of the array (index&nbsp;<code>n - 1</code>). Your&nbsp;<strong>score</strong>&nbsp;is the&nbsp;<strong>sum</strong>&nbsp;of all&nbsp;<code>nums[j]</code>&nbsp;for each index&nbsp;<code>j</code>&nbsp;you visited in the array.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum score</strong>&nbsp;you can get</em>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-1,-2,4,-7,3], k = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,-5,-2,4,0,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation:</strong> You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
<strong>Output:</strong> 0
</pre>



<p><strong>Constraints:</strong></p>



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



<h2><strong>Solution: DP + Monotonic Queue</strong></h2>



<p>dp[i] = nums[i] + max(dp[j]) i &#8211; k &lt;= j &lt; i</p>



<p>Brute force time complexity: O(n*k) =&gt; TLE</p>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-1.png" alt="" class="wp-image-7833" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-2.png" alt="" class="wp-image-7834" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-3.png" alt="" class="wp-image-7835" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/12/1696-ep376-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3 / TLE</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua 52/58 Passed (TLE)
class Solution:  
  def maxResult(self, nums: List[int], k: int) -&amp;gt; int:
    @lru_cache(None)
    def dp(i: int) -&amp;gt; int:
      return nums[0] if i == 0 else nums[i] + max(dp(j) for j in range(max(0, i - k), i))
    return dp(len(nums) - 1)</pre>
</div></div>



<p>This problem can be reduced to find the maximum for a sliding window that can be solved by monotonic queue.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n+k) -> O(k)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxResult(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    vector&lt;int&gt; dp(n);
    deque&lt;int&gt; q{{0}};
    dp[0] = nums[0];    
    for (int i = 1; i &lt; n; ++i) {
      dp[i] = nums[i] + dp[q.front()];
      while (!q.empty() &amp;&amp; dp[i] &gt;= dp[q.back()]) q.pop_back();
      while (!q.empty() &amp;&amp; i - q.front() &gt;= k) q.pop_front();      
      q.push_back(i);      
    }
    return dp[n - 1];
  }
};</pre>

</div><h2 class="tabtitle">C++/O(n) Space</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxResult(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    deque&lt;pair&lt;int, int&gt;&gt; q{{nums[0], 0}};
    for (int i = 1; i &lt; n; ++i) {      
      const int cur = nums[i] + q.front().first;      
      while (!q.empty() &amp;&amp; cur &gt;= q.back().first) 
        q.pop_back();
      while (!q.empty() &amp;&amp; i - q.front().second &gt;= k) 
        q.pop_front();      
      q.emplace_back(cur, i);
    }
    for (const auto&amp; [v, i] : q)
      if (i == n - 1) return v;
    return 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1696-jump-game-vi/">花花酱 LeetCode 1696. Jump Game VI</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1696-jump-game-vi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1499. Max Value of Equation</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-1499-max-value-of-equation/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-1499-max-value-of-equation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Jun 2020 22:07:06 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7011</guid>

					<description><![CDATA[<p>Given an&#160;array&#160;points&#160;containing the coordinates of points on a 2D plane,&#160;sorted by the x-values, where&#160;points[i] = [xi, yi]&#160;such that&#160;xi&#160;&#60; xj&#160;for all&#160;1 &#60;= i &#60; j &#60;=&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1499-max-value-of-equation/">花花酱 LeetCode 1499. Max Value of Equation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1499. Max Value of Equation - 刷题找工作 EP340" width="500" height="281" src="https://www.youtube.com/embed/GahRKbpoQVQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an&nbsp;array&nbsp;<code>points</code>&nbsp;containing the coordinates of points on a 2D plane,&nbsp;sorted by the x-values, where&nbsp;<code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>&nbsp;such that&nbsp;<code>x<sub>i</sub>&nbsp;&lt; x<sub>j</sub></code>&nbsp;for all&nbsp;<code>1 &lt;= i &lt; j &lt;= points.length</code>. You are also given an integer&nbsp;<code>k</code>.</p>



<p>Find the&nbsp;<em>maximum value of the equation&nbsp;</em><code>y<sub>i</sub>&nbsp;+ y<sub>j</sub>&nbsp;+ |x<sub>i</sub>&nbsp;- x<sub>j</sub>|</code>&nbsp;where&nbsp;<code>|x<sub>i</sub>&nbsp;- x<sub>j</sub>|&nbsp;&lt;= k</code>&nbsp;and&nbsp;<code>1 &lt;= i &lt; j &lt;= points.length</code>. It is guaranteed that there exists at least one pair of points that satisfy the constraint&nbsp;<code>|x<sub>i</sub>&nbsp;- x<sub>j</sub>|&nbsp;&lt;= k</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> The first two points satisfy the condition |x<sub>i</sub>&nbsp;- x<sub>j</sub>| &lt;= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> points = [[0,0],[3,0],[9,2]], k = 3
<strong>Output:</strong> 3
<strong>Explanation: </strong>Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= points.length &lt;= 10^5</code></li><li><code>points[i].length == 2</code></li><li><code>-10^8&nbsp;&lt;= points[i][0], points[i][1] &lt;= 10^8</code></li><li><code>0 &lt;= k &lt;= 2 * 10^8</code></li><li><code>points[i][0] &lt; points[j][0]</code>&nbsp;for all&nbsp;<code>1 &lt;= i &lt; j &lt;= points.length</code></li><li><code>x<sub>i</sub></code>&nbsp;form a strictly increasing sequence.</li></ul>



<h2><strong>Observation</strong></h2>



<p>Since xj &gt; xi, so |xi &#8211; xj| + yi + yj =&gt; xj + yj + (yi &#8211; xi)<br>We want to have yi &#8211; xi as large as possible while need to make sure xj &#8211; xi &lt;= k.</p>



<h2><strong>Solution 1: Priority Queue / Heap</strong></h2>



<p>Put all the points processed so far onto the heap as (y-x, x) sorted by y-x in descending order.<br>Each new point (x_j, y_j), find the largest y-x such that x_j &#8211; x &lt;= k.</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxValueOfEquation(vector&lt;vector&lt;int&gt;&gt;&amp; points, int k) {
    priority_queue&lt;pair&lt;int, int&gt;&gt; q; // {y - x, x}    
    q.emplace(0, -1e9);
    int ans = INT_MIN;
    for (const auto&amp; p : points) {
      const int x = p[0], y = p[1];
      while (!q.empty() &amp;&amp; x - q.top().second &gt; k) q.pop();
      if (!q.empty())
        ans = max(ans, x + y + q.top().first);
      q.emplace(y - x, x);
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Monotonic Queue</strong></h2>



<p><br>Maintain a monotonic queue:<br>1. The queue is sorted by y &#8211; x in descending order. <br>2. Pop then front element when xj &#8211; x_front &gt; k, they can&#8217;t be used anymore.<br>3. Record the max of {xj + yj + (y_front &#8211; x_front)}<br>4. Pop the back element when yj &#8211; xj &gt; y_back &#8211; x_back, they are smaller and lefter. Won&#8217;t be useful anymore.<br>5. Finally, push the j-th element onto the queue.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxValueOfEquation(vector&lt;vector&lt;int&gt;&gt;&amp; points, int k) {    
    deque&lt;pair&lt;int, int&gt;&gt; q; // {y - x, x} Sort by y - x.
    int ans = INT_MIN;
    for (const auto&amp; p : points) {
      const int xj = p[0];
      const int yj = p[1];
      // Remove invalid points, e.g. xj - xi &gt; k
      while (!q.empty() &amp;&amp; xj - q.front().second &gt; k)
        q.pop_front();
      if (!q.empty())
        ans = max(ans, xj + yj + q.front().first);      
      while (!q.empty() &amp;&amp; yj - xj &gt;= q.back().first) 
        q.pop_back();
      q.emplace_back(yj - xj, xj);
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
  public int findMaxValueOfEquation(int[][] points, int k) {
    var q = new ArrayDeque&lt;Integer&gt;();
    int ans = Integer.MIN_VALUE;
    for (int i = 0; i &lt; points.length; ++i) {
      int xj = points[i][0];
      int yj = points[i][1];
      
      while (!q.isEmpty() &amp;&amp; xj - points[q.getFirst()][0] &gt; k) {
        q.removeFirst();
      }
      
      if (!q.isEmpty()) {
        ans = Math.max(ans, xj + yj 
                + points[q.getFirst()][1] - points[q.getFirst()][0]);
      }
      
      while (!q.isEmpty() &amp;&amp; yj - xj 
                &gt;= points[q.getLast()][1] - points[q.getLast()][0]) {
        q.removeLast();
      }
      
      q.offer(i);
    }
    return ans;
  }
}</pre>

</div><h2 class="tabtitle">python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def findMaxValueOfEquation(self, points: List[List[int]], k: int) -&gt; int:
    ans = float('-inf')
    q = deque() # {(y - x, x)}
    for x, y in points:
      while q and x - q[0][1] &gt; k: q.popleft()
      if q: ans = max(ans, x + y + q[0][0])
      while q and y - x &gt;= q[-1][0]: q.pop()
      q.append((y - x, x))
    return ans</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1499-max-value-of-equation/">花花酱 LeetCode 1499. Max Value of Equation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/queue/leetcode-1499-max-value-of-equation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 04 May 2020 04:21:37 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[monotonic queue]]></category>
		<category><![CDATA[multiset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6701</guid>

					<description><![CDATA[<p>Given an&#160;array of integers&#160;nums&#160;and an&#160;integer&#160;limit, return the size of the longest continuous subarray such that the absolute difference between any two elements is less than&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/">花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit EP323" width="500" height="375" src="https://www.youtube.com/embed/p8-f0_CwWLk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an&nbsp;array of integers&nbsp;<code>nums</code>&nbsp;and an&nbsp;integer&nbsp;<code>limit</code>, return the size of the longest continuous subarray such that the absolute difference between any two elements is less than or equal to&nbsp;<code>limit</code><em>.</em></p>



<p>In case there is no subarray satisfying the given condition return 0.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [8,2,4,7], limit = 4
<strong>Output:</strong> 2 
<strong>Explanation:</strong> All subarrays are: 
[8] with maximum absolute diff |8-8| = 0 &lt;= 4.
[8,2] with maximum absolute diff |8-2| = 6 &gt; 4. 
[8,2,4] with maximum absolute diff |8-2| = 6 &gt; 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 &gt; 4.
[2] with maximum absolute diff |2-2| = 0 &lt;= 4.
[2,4] with maximum absolute diff |2-4| = 2 &lt;= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 &gt; 4.
[4] with maximum absolute diff |4-4| = 0 &lt;= 4.
[4,7] with maximum absolute diff |4-7| = 3 &lt;= 4.
[7] with maximum absolute diff |7-7| = 0 &lt;= 4. 
Therefore, the size of the longest subarray is 2.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,1,2,4,7,2], limit = 5
<strong>Output:</strong> 4 
<strong>Explanation:</strong> The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 &lt;= 5.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,2,2,4,4,2,2], limit = 0
<strong>Output:</strong> 3
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>1 &lt;= nums[i] &lt;= 10^9</code></li><li><code>0 &lt;= limit &lt;= 10^9</code></li></ul>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-1.png" alt="" class="wp-image-6706" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-2.png" alt="" class="wp-image-6707" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1438-ep323-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<h2><strong>Solution 1: Sliding Window + TreeSet</strong></h2>



<p>Use a treeset to maintain a range of [l, r] such that max(nums[l~r]) &#8211; min(nums[l~r]) &lt;= limit.<br>Every time, we add nums[r] into the tree, and move l towards r to keep the max diff under limit.</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums, int limit) {
    multiset&lt;int&gt; s;
    int l = 0;
    int ans = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      s.insert(nums[r]);
      while (*rbegin(s) - *begin(s) &gt; limit)
        s.erase(s.equal_range(nums[l++]).first);
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Dual Monotonic Queue</strong></h2>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/">https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/</a></p>



<p>We want to maintain a range [l, r] that max(nums[l~r]) &#8211; min(nums[l~r]) &lt;= limit, to track the max/min of a range efficiently we could use monotonic queue. One for max and one for min.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums, int limit) {
    deque&lt;int&gt; max_q;
    deque&lt;int&gt; min_q;
    int ans = 0;
    int l = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      while (!min_q.empty() &amp;&amp; nums[r] &lt; min_q.back()) 
        min_q.pop_back();
      while (!max_q.empty() &amp;&amp; nums[r] &gt; max_q.back()) 
        max_q.pop_back();
      min_q.push_back(nums[r]);
      max_q.push_back(nums[r]);
      while (max_q.front() - min_q.front() &gt; limit) {
        if (max_q.front() == nums[l]) max_q.pop_front();
        if (min_q.front() == nums[l]) min_q.pop_front();
        ++l;
      }
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/">花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1425. Constrained Subset Sum</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Apr 2020 07:58:26 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic queue]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6668</guid>

					<description><![CDATA[<p>Given an integer array&#160;nums&#160;and an integer&#160;k, return the maximum sum of a&#160;non-empty&#160;subset of that array such that for every&#160;two&#160;consecutive&#160;integers in the subset,&#160;nums[i]&#160;and&#160;nums[j], where&#160;i &#60; j,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/">花花酱 LeetCode 1425. Constrained Subset Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1425. Constrained Subset Sum - 刷题找工作 EP321" width="500" height="375" src="https://www.youtube.com/embed/B5fa989qz4U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



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



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



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,2,-10,5,20], k = 2
<strong>Output:</strong> 37
<strong>Explanation:</strong> The subset is [10, 2, 5, 20].
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,-2,-3], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> The subset must be non-empty, so we choose the largest number.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,-2,-10,-5,20], k = 2
<strong>Output:</strong> 23
<strong>Explanation:</strong> The subset is [10, -2, -5, 20].
</pre>



<p><strong>Constraints:</strong></p>



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



<h2><strong>Solution: DP / Sliding window / monotonic queue</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1425-ep231-1.png" alt="" class="wp-image-6673" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1425-ep231-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1425-ep231-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1425-ep231-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i] := max sum of a subset that include nums[i]<br>dp[i] := max(dp[i-1], dp[i-2], &#8230;, dp[i-k-1], 0) + nums[i]</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int constrainedSubsetSum(vector&lt;int&gt;&amp; nums, int k) {    
    const int n = nums.size();
    vector&lt;int&gt; dp(n);
    multiset&lt;int&gt; s{INT_MIN};
    int ans = INT_MIN;
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (i &gt; k) s.erase(s.equal_range(dp[i - k - 1]).first);
      dp[i] = max(*rbegin(s), 0) + nums[i];
      s.insert(dp[i]);
      ans = max(ans, dp[i]);
    }
    return ans;
  }
};</pre>
</div></div>



<p>Use a monotonic queue to track the maximum of a sliding window dp[i-k-1] ~ dp[i-1].</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua 184 ms
class Solution {
public:
  int constrainedSubsetSum(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    vector&lt;int&gt; dp(n);
    deque&lt;int&gt; q;
    int ans = INT_MIN;
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (i &gt; k &amp;&amp; q.front() == i - k - 1)
        q.pop_front();
      dp[i] = (q.empty() ? 0 : max(dp[q.front()], 0))
             + nums[i];
      while (!q.empty() &amp;&amp; dp[i] &gt;= dp[q.back()])
        q.pop_back();
      q.push_back(i);
      ans = max(ans, dp[i]);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/">花花酱 LeetCode 1425. Constrained Subset Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
