<?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>Queue Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/queue/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/queue/</link>
	<description></description>
	<lastBuildDate>Mon, 13 Jul 2020 00:26:04 +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>Queue Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/queue/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Jul 2020 04:22:08 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7071</guid>

					<description><![CDATA[<p>Given the array&#160;nums&#160;consisting of&#160;n&#160;positive integers. You computed the sum of all non-empty continous subarrays from&#160;the array and then sort them in non-decreasing order, creating a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/">花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</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 1508. Range Sum of Sorted Subarray Sums - 刷题找工作 EP343" width="500" height="281" src="https://www.youtube.com/embed/6UJEMVmMJDw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the array&nbsp;<code>nums</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;positive integers. You computed the sum of all non-empty continous subarrays from&nbsp;the array and then sort them in non-decreasing order, creating a new array of&nbsp;<code>n * (n + 1) / 2</code>&nbsp;numbers.</p>



<p><em>Return the sum of the numbers from index&nbsp;</em><code>left</code><em>&nbsp;to index&nbsp;</em><code>right</code>&nbsp;(<strong>indexed from 1</strong>)<em>, inclusive, in the&nbsp;new array.&nbsp;</em>Since the answer can be a huge number return it modulo 10^9 + 7.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 5
<strong>Output:</strong> 13 
<strong>Explanation:</strong> All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 3, right = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 10
<strong>Output:</strong> 50
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^3</code></li><li><code>nums.length == n</code></li><li><code>1 &lt;= nums[i] &lt;= 100</code></li><li><code>1 &lt;= left &lt;= right&nbsp;&lt;= n * (n + 1) / 2</code></li></ul>



<h2><strong>Solution 1: Brute Force</strong></h2>



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



<p>Find sums of all the subarrays and sort the values.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;
    vector&lt;int&gt; sums;
    for (int i = 0; i &lt; n; ++i)      
      for (int j = i, sum = 0; j &lt; n; ++j)
        sums.push_back(sum += nums[j]);
    sort(begin(sums), end(sums));
    return accumulate(begin(sums) + left - 1, begin(sums) + right, 0LL) % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public int rangeSum(int[] nums, int n, int left, int right) {
    final int kMod = (int)(1e9 + 7);
    int[] sums = new int[n * (n + 1) / 2];
    int idx = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = i, sum = 0; j &lt; n; ++j, ++idx)
        sums[idx] = sum += nums[j];
    Arrays.sort(sums);
    int ans = 0;
    for (int i = left; i &lt;= right; ++i)
      ans = (ans + sums[i - 1]) % kMod;
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def rangeSum(self, nums: List[int], n: int, left: int, right: int) -&gt; int:
    sums = []
    for i in range(n):
      s = 0
      for j in range(i, n):
        s += nums[j]
        sums.append(s)
    sums.sort()
    return sum(sums[left - 1:right])</pre>
</div></div>



<h2><strong>Solution 2: Priority Queue</strong> <strong>/ Min Heap</strong></h2>



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



<p>For each subarray, start with one element e.g nums[i], put them into a priority queue (min heap). Each time, we have the smallest subarray sum, and extend that subarray and put the new sum back into priority queue. Thought it has the same time complexity as the brute force one in worst case, but space complexity can be reduce to O(n).</p>



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



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

<pre class="crayon-plain-tag">struct Entry {
  int sum;
  int i;
  bool operator&lt;(const Entry&amp; e) const { return sum &gt; e.sum; }
};

class Solution {
public:
  int rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;
    priority_queue&lt;Entry&gt; q; // Sort by e.sum in descending order.
    for (int i = 0; i &lt; n; ++i)
      q.push({nums[i], i});
    long ans = 0;
    for (int j = 1; j &lt;= right; ++j) {
      const auto e = std::move(q.top()); q.pop();
      if (j &gt;= left) ans += e.sum;
      if (e.i + 1 &lt; n) q.push({e.sum + nums[e.i + 1], e.i + 1});
    }
    return ans % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">import java.util.AbstractMap;
class Solution {
  public int rangeSum(int[] nums, int n, int left, int right) {
    final int kMod = (int)(1e9 + 7);
    var q = new PriorityQueue&lt;Map.Entry&lt;Integer, Integer&gt;&gt;((a, b) -&gt; a.getKey() - b.getKey());
    for (int i = 0; i &lt; n; ++i)
      q.offer(new AbstractMap.SimpleEntry&lt;&gt;(nums[i], i));
    
    int ans = 0;
    for (int k = 1; k &lt;= right; ++k) {      
      var e = q.poll();
      int sum = e.getKey();
      int i = e.getValue();
      if (k &gt;= left) 
        ans = (ans + sum) % kMod;
      if (i + 1 &lt; n) 
        q.offer(new AbstractMap.SimpleEntry&lt;&gt;(sum + nums[i + 1], i + 1));
    }
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def rangeSum(self, nums: List[int], n: int, left: int, right: int) -&gt; int:
    q = [(num, i) for i, num in enumerate(nums)]
    heapq.heapify(q)
    ans = 0
    for k in range(1, right + 1):
      s, i = heapq.heappop(q)
      if k &gt;= left:
        ans += s
      if i + 1 &lt; n:
        heapq.heappush(q, (s + nums[i + 1], i + 1))
    return ans % int(1e9 + 7)</pre>
</div></div>



<h2><strong>Solution 3: Binary Search + Sliding Window</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-3.png" alt="" class="wp-image-7095" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-3-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/07/1508-ep343-4.png" alt="" class="wp-image-7096" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1508-ep343-4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Use binary search to find S s.t. that there are at least k subarrys have sum &lt;= S.</p>



<p>Given S, we can use sliding window to count how many subarrays have sum &lt;= S and their total sum.</p>



<p>ans = sums_of_first(right) &#8211; sums_of_first(left &#8211; 1).</p>



<p>Time complexity: O(n * log(sum(nums))<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 rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;    
    // Returns number of subarrays that have 
    // sum &lt;= target and their total sum.
    auto countAndSum = [&amp;](int target) -&gt; pair&lt;int, long&gt; {
      int count = 0;
      long cur = 0;
      long sum = 0;
      long total_sum = 0;
      for (long j = 0, i = 0; j &lt; n; ++j) {
        cur += nums[j];
        sum += nums[j] * (j - i + 1);
        while (cur &gt; target) {          
          sum -= cur;
          cur -= nums[i++];
        }        
        count += j - i + 1;
        total_sum += sum;
      }
      return {count, total_sum};
    };
    
    // Returns the total sums of smallest k subarrays.
    // Use binary search to find the smallest sum l s.t. 
    // there are at least k of subarrays have sums &lt;= l.
    const int min_sum = *min_element(begin(nums), end(nums));
    const int max_sum = accumulate(begin(nums), end(nums), 0) + 1;
    auto sumOfFirstK = [&amp;](int k) -&gt; long {
      int l = min_sum;
      int r = max_sum;
      while (l &lt; r) {
        int mid = l + (r - l) / 2;
        if (countAndSum(mid).first &gt;= k)
          r = mid;
        else
          l = mid + 1;
      }      
      const auto [count, sum] = countAndSum(l);
      // There can be more subarrays have the same sum of l.      
      return sum - l * (count - k);
    };
    
    return (sumOfFirstK(right) - sumOfFirstK(left - 1)) % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/">花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</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-1508-range-sum-of-sorted-subarray-sums/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 933. Number of Recent Calls</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 04 Nov 2018 08:20:59 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4248</guid>

					<description><![CDATA[<p>Problem Write a class RecentCounter to count recent requests. It has only one method: ping(int t), where t represents some time in milliseconds. Return the number of pings that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/">花花酱 LeetCode 933. Number of Recent Calls</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Write a class <code>RecentCounter</code> to count recent requests.</p>
<p>It has only one method: <code>ping(int t)</code>, where t represents some time in milliseconds.</p>
<p>Return the number of <code>ping</code>s that have been made from 3000 milliseconds ago until now.</p>
<p>Any ping with time in <code>[t - 3000, t]</code> will count, including the current ping.</p>
<p>It is guaranteed that every call to <code>ping</code> uses a strictly larger value of <code>t</code> than before.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>inputs = <span id="example-input-1-1">["RecentCounter","ping","ping","ping","ping"]</span>, inputs = <span id="example-input-1-2">[[],[1],[100],[3001],[3002]]</span>
<strong>Output: </strong><span id="example-output-1">[null,1,2,3,3]</span></pre>
<p><strong>Note:</strong></p>
<ol>
<li>Each test case will have at most <code>10000</code> calls to <code>ping</code>.</li>
<li>Each test case will call <code>ping</code> with strictly increasing values of <code>t</code>.</li>
<li>Each call to ping will have <code>1 &lt;= t &lt;= 10^9</code>.</li>
</ol>
<h1>Solution: Queue</h1>
<p>Use a FIFO queue to track all the previous pings that are within 3000 ms to current.</p>
<p>Time complexity: Avg O(1), Total O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class RecentCounter {
public:
    RecentCounter() {}
    
    int ping(int t) {
      while (!q.empty() &amp;&amp; t - q.front() &gt; 3000) q.pop();
      q.push(t);
      return q.size();
    }
private:
  queue&lt;int&gt; q;
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/">花花酱 LeetCode 933. Number of Recent Calls</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-933-number-of-recent-calls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
