<?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>heap Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/heap/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/heap/</link>
	<description></description>
	<lastBuildDate>Sun, 17 Apr 2022 21:19:36 +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>heap Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/heap/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2242. Maximum Score of a Node Sequence</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Apr 2022 06:16:40 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9662</guid>

					<description><![CDATA[<p>There is an&#160;undirected&#160;graph with&#160;n&#160;nodes, numbered from&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;scores&#160;of length&#160;n&#160;where&#160;scores[i]&#160;denotes the score of node&#160;i. You are also given a 2D integer&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/">花花酱 LeetCode 2242. Maximum Score of a Node Sequence</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is an&nbsp;<strong>undirected</strong>&nbsp;graph with&nbsp;<code>n</code>&nbsp;nodes, numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>scores</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where&nbsp;<code>scores[i]</code>&nbsp;denotes the score of node&nbsp;<code>i</code>. You are also given a 2D integer array&nbsp;<code>edges</code>&nbsp;where&nbsp;<code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists an&nbsp;<strong>undirected</strong>&nbsp;edge connecting nodes&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>A node sequence is&nbsp;<strong>valid</strong>&nbsp;if it meets the following conditions:</p>



<ul><li>There is an edge connecting every pair of&nbsp;<strong>adjacent</strong>&nbsp;nodes in the sequence.</li><li>No node appears more than once in the sequence.</li></ul>



<p>The score of a node sequence is defined as the&nbsp;<strong>sum</strong>&nbsp;of the scores of the nodes in the sequence.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum score</strong>&nbsp;of a valid node sequence with a length of&nbsp;</em><code>4</code><em>.&nbsp;</em>If no such sequence exists, return<em>&nbsp;</em><code>-1</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The figure above shows the graph and the chosen node sequence [0,1,2,3].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.
The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/17/ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.
</pre>



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



<ul><li><code>n == scores.length</code></li><li><code>4 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li><li><code>1 &lt;= scores[i] &lt;= 10<sup>8</sup></code></li><li><code>0 &lt;= edges.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt;= n - 1</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li>There are no duplicate edges.</li></ul>



<h2><strong>Solution: Greedy / Top3 neighbors</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png" alt="" class="wp-image-9667" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png" alt="" class="wp-image-9668" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png" alt="" class="wp-image-9669" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png" alt="" class="wp-image-9671" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png" alt="" class="wp-image-9673" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Since |E| is already 5*10<sup>4</sup>, we can&#8217;t enumerate all possible sequences. We must do in O(|E|) or O(|E|log|E|).</p>



<p>Enumerate all the edges, we have a pair of node a, b. To get the optimal answer, we just need to find the largest neighbor of a and b, which we call c, d respectively. Just need to make sure a, b, c, d are unique. i.e. c != d, c != b and d != a. Since the a&#8217;s largest neighbor can be either b or d. We can&#8217;t just store the largest neighbor, but top 3 instead for each node to avoid duplications.</p>



<p>Time complexity: O(|E|*9)<br>Space complexity: O(|V|*3)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumScore(vector&lt;int&gt;&amp; scores, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    const int n = scores.size();
    vector&lt;set&lt;pair&lt;int, int&gt;&gt;&gt; top3(n);
    for (const auto&amp; e : edges) {      
      top3[e[0]].emplace(scores[e[1]], e[1]);
      top3[e[1]].emplace(scores[e[0]], e[0]);
      if (top3[e[0]].size() &gt; 3) top3[e[0]].erase(begin(top3[e[0]]));
      if (top3[e[1]].size() &gt; 3) top3[e[1]].erase(begin(top3[e[1]]));
    }
    int ans = -1;
    for (const auto&amp; e : edges) {
      const int a = e[0], b = e[1], sa = scores[a], sb = scores[b];
      for (const auto&amp; [sc, c] : top3[a])
        for (const auto&amp; [sd, d] : top3[b])          
          if (sa + sb + sc + sd &gt; ans &amp;&amp; c != b &amp;&amp; c != d &amp;&amp; d != a)
            ans = sa + sb + sc + sd;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/">花花酱 LeetCode 2242. Maximum Score of a Node Sequence</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/greedy/leetcode-2242-maximum-score-of-a-node-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2208. Minimum Operations to Halve Array Sum</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Mar 2022 12:21:32 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[priority_queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9580</guid>

					<description><![CDATA[<p>You are given an array&#160;nums&#160;of positive integers. In one operation, you can choose&#160;any&#160;number from&#160;nums&#160;and reduce it to&#160;exactly&#160;half the number. (Note that you may choose this&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/">花花酱 LeetCode 2208. Minimum Operations to Halve Array 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[
<p>You are given an array&nbsp;<code>nums</code>&nbsp;of positive integers. In one operation, you can choose&nbsp;<strong>any</strong>&nbsp;number from&nbsp;<code>nums</code>&nbsp;and reduce it to&nbsp;<strong>exactly</strong>&nbsp;half the number. (Note that you may choose this reduced number in future operations.)</p>



<p>Return<em>&nbsp;the&nbsp;<strong>minimum</strong>&nbsp;number of operations to reduce the sum of&nbsp;</em><code>nums</code><em>&nbsp;by&nbsp;<strong>at least</strong>&nbsp;half.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,19,8,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
The following is one of the ways to reduce the sum by at least half:
Pick the number 19 and reduce it to 9.5.
Pick the number 9.5 and reduce it to 4.75.
Pick the number 8 and reduce it to 4.
The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. 
The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 &gt;= 33/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,8,20]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The initial sum of nums is equal to 3 + 8 + 20 = 31.
The following is one of the ways to reduce the sum by at least half:
Pick the number 20 and reduce it to 10.
Pick the number 10 and reduce it to 5.
Pick the number 3 and reduce it to 1.5.
The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. 
The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 &gt;= 31/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
</pre>



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



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



<h2><strong>Solution: Greedy + PriorityQueue/Max Heap</strong></h2>



<p>Always half the largest number, put all the numbers onto a max heap (priority queue), extract the largest one, and put reduced number back.</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 halveArray(vector&lt;int&gt;&amp; nums) {
    double sum = accumulate(begin(nums), end(nums), 0.0);
    priority_queue&lt;double&gt; q;
    for (int num : nums) q.push(num);
    int ans = 0;
    for (double cur = sum; cur &gt; sum / 2; ++ans) {    
      double num = q.top(); q.pop();
      cur -= num / 2;
      q.push(num / 2);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/">花花酱 LeetCode 2208. Minimum Operations to Halve Array 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/heap/leetcode-2208-minimum-operations-to-halve-array-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1962. Remove Stones to Minimize the Total</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1962-remove-stones-to-minimize-the-total/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1962-remove-stones-to-minimize-the-total/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 22:20:09 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority_queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9335</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;piles, where&#160;piles[i]&#160;represents the number of stones in the&#160;ith&#160;pile, and an integer&#160;k. You should apply the following operation&#160;exactly&#160;k&#160;times: Choose any&#160;piles[i]&#160;and&#160;remove&#160;floor(piles[i] / 2)&#160;stones&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1962-remove-stones-to-minimize-the-total/">花花酱 LeetCode 1962. Remove Stones to Minimize the Total</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>piles</code>, where&nbsp;<code>piles[i]</code>&nbsp;represents the number of stones in the&nbsp;<code>i<sup>th</sup></code>&nbsp;pile, and an integer&nbsp;<code>k</code>. You should apply the following operation&nbsp;<strong>exactly</strong>&nbsp;<code>k</code>&nbsp;times:</p>



<ul><li>Choose any&nbsp;<code>piles[i]</code>&nbsp;and&nbsp;<strong>remove</strong>&nbsp;<code>floor(piles[i] / 2)</code>&nbsp;stones from it.</li></ul>



<p><strong>Notice</strong>&nbsp;that you can apply the operation on the&nbsp;<strong>same</strong>&nbsp;pile more than once.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;possible total number of stones remaining after applying the&nbsp;</em><code>k</code><em>&nbsp;operations</em>.</p>



<p><code>floor(x)</code>&nbsp;is the&nbsp;<strong>greatest</strong>&nbsp;integer that is&nbsp;<strong>smaller</strong>&nbsp;than or&nbsp;<strong>equal</strong>&nbsp;to&nbsp;<code>x</code>&nbsp;(i.e., rounds&nbsp;<code>x</code>&nbsp;down).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> piles = [5,4,9], k = 2
<strong>Output:</strong> 12
<strong>Explanation:</strong>&nbsp;Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> piles = [4,3,6,7], k = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong>&nbsp;Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
The total number of stones in [2,3,3,4] is 12.
</pre>



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



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



<h2><strong>Solution: Greedy / Heap</strong></h2>



<p>Always choose the largest pile to remove.</p>



<p>Time complexity: O(n + klogn)<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 minStoneSum(vector&lt;int&gt;&amp; piles, int k) {
    int total = accumulate(begin(piles), end(piles), 0);
    priority_queue&lt;int&gt; q(begin(piles), end(piles));
    while (k--) {
      int curr = q.top(); q.pop();
      int remove = curr / 2;
      total -= remove;
      q.push(curr - remove);
    }
    return total;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1962-remove-stones-to-minimize-the-total/">花花酱 LeetCode 1962. Remove Stones to Minimize the Total</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/greedy/leetcode-1962-remove-stones-to-minimize-the-total/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1942. The Number of the Smallest Unoccupied Chair</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1942-the-number-of-the-smallest-unoccupied-chair/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1942-the-number-of-the-smallest-unoccupied-chair/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 13:50:08 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9308</guid>

					<description><![CDATA[<p>There is a party where&#160;n&#160;friends numbered from&#160;0&#160;to&#160;n - 1&#160;are attending. There is an&#160;infinite&#160;number of chairs in this party that are numbered from&#160;0&#160;to&#160;infinity. When a friend&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1942-the-number-of-the-smallest-unoccupied-chair/">花花酱 LeetCode 1942. The Number of the Smallest Unoccupied Chair</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a party where&nbsp;<code>n</code>&nbsp;friends numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;are attending. There is an&nbsp;<strong>infinite</strong>&nbsp;number of chairs in this party that are numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>infinity</code>. When a friend arrives at the party, they sit on the unoccupied chair with the&nbsp;<strong>smallest number</strong>.</p>



<ul><li>For example, if chairs&nbsp;<code>0</code>,&nbsp;<code>1</code>, and&nbsp;<code>5</code>&nbsp;are occupied when a friend comes, they will sit on chair number&nbsp;<code>2</code>.</li></ul>



<p>When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>times</code>&nbsp;where&nbsp;<code>times[i] = [arrival<sub>i</sub>, leaving<sub>i</sub>]</code>, indicating the arrival and leaving times of the&nbsp;<code>i<sup>th</sup></code>&nbsp;friend respectively, and an integer&nbsp;<code>targetFriend</code>. All arrival times are&nbsp;<strong>distinct</strong>.</p>



<p>Return<em>&nbsp;the&nbsp;<strong>chair number</strong>&nbsp;that the friend numbered&nbsp;</em><code>targetFriend</code><em>&nbsp;will sit on</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> times = [[1,4],[2,3],[4,6]], targetFriend = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> 
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> times = [[3,10],[1,5],[2,6]], targetFriend = 0
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
</pre>



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



<ul><li><code>n == times.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li><li><code>times[i].length == 2</code></li><li><code>1 &lt;= arrival<sub>i</sub>&nbsp;&lt; leaving<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= targetFriend &lt;= n - 1</code></li><li>Each&nbsp;<code>arrival<sub>i</sub></code>&nbsp;time is&nbsp;<strong>distinct</strong>.</li></ul>



<h2><strong>Solution: Treeset + Simulation</strong></h2>



<p>Use a treeset to track available chairs, sort events by time.<br>note: process leaving events first.</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 smallestChair(vector&lt;vector&lt;int&gt;&gt;&amp; times, int targetFriend) {
    const int n = times.size();
    vector&lt;pair&lt;int, int&gt;&gt; arrival(n);
    vector&lt;pair&lt;int, int&gt;&gt; leaving(n);
    for (int i = 0; i &lt; n; ++i) {
      arrival[i] = {times[i][0], i};
      leaving[i] = {times[i][1], i};
    }
    vector&lt;int&gt; pos(n);
    iota(begin(pos), end(pos), 0); // pos = [0, 1, ..., n -1]
    set&lt;int&gt; aval(begin(pos), end(pos));    
    sort(begin(arrival), end(arrival));
    sort(begin(leaving), end(leaving));
    for (int i = 0, j = 0; i &lt; n; ++i) {
      const auto [t, u] = arrival[i];
      while (j &lt; n &amp;&amp; leaving[j].first &lt;= t)        
        aval.insert(pos[leaving[j++].second]);        
      aval.erase(pos[u] = *begin(aval));      
      if (u == targetFriend) return pos[u];
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1942-the-number-of-the-smallest-unoccupied-chair/">花花酱 LeetCode 1942. The Number of the Smallest Unoccupied Chair</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/priority-queue/leetcode-1942-the-number-of-the-smallest-unoccupied-chair/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2054. Two Best Non-Overlapping Events</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Nov 2021 02:16:37 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8653</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;2D integer array of&#160;events&#160;where&#160;events[i] = [startTimei, endTimei, valuei]. The&#160;ith&#160;event starts at&#160;startTimeiand ends at&#160;endTimei, and if you attend this event, you will receive&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/">花花酱 LeetCode 2054. Two Best Non-Overlapping Events</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array of&nbsp;<code>events</code>&nbsp;where&nbsp;<code>events[i] = [startTime<sub>i</sub>, endTime<sub>i</sub>, value<sub>i</sub>]</code>. The&nbsp;<code>i<sup>th</sup></code>&nbsp;event starts at&nbsp;<code>startTime<sub>i</sub></code>and ends at&nbsp;<code>endTime<sub>i</sub></code>, and if you attend this event, you will receive a value of&nbsp;<code>value<sub>i</sub></code>. You can choose&nbsp;<strong>at most</strong>&nbsp;<strong>two</strong>&nbsp;<strong>non-overlapping</strong>&nbsp;events to attend such that the sum of their values is&nbsp;<strong>maximized</strong>.</p>



<p>Return&nbsp;<em>this&nbsp;<strong>maximum</strong>&nbsp;sum.</em></p>



<p>Note that the start time and end time is&nbsp;<strong>inclusive</strong>: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time&nbsp;<code>t</code>, the next event must start at or after&nbsp;<code>t + 1</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/09/21/picture5.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,3,2],[4,5,2],[2,4,3]]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/09/21/picture1.png" alt="Example 1 Diagram"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,3,2],[4,5,2],[1,5,5]]
<strong>Output:</strong> 5
<strong>Explanation: </strong>Choose event 2 for a sum of 5.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/09/21/picture3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,5,3],[1,5,1],[6,6,5]]
<strong>Output:</strong> 8
<strong>Explanation: </strong>Choose events 0 and 2 for a sum of 3 + 5 = 8.</pre>



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



<ul><li><code>2 &lt;= events.length &lt;= 10<sup>5</sup></code></li><li><code>events[i].length == 3</code></li><li><code>1 &lt;= startTime<sub>i</sub>&nbsp;&lt;= endTime<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= value<sub>i</sub>&nbsp;&lt;= 10<sup>6</sup></code></li></ul>



<h2><strong>Solution: Sort + Heap</strong></h2>



<p>Sort events by start time, process them from left to right.</p>



<p>Use a min heap to store the events processed so far, a variable cur to track the max value of a non-overlapping event.</p>



<p>For a given event, pop all non-overlapping events whose end time is smaller than its start time and update cur.</p>



<p>ans = max(val + cur)</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 maxTwoEvents(vector&lt;vector&lt;int&gt;&gt;&amp; events) {
    using E = pair&lt;int,int&gt;;
    sort(begin(events), end(events));
    priority_queue&lt;E, vector&lt;E&gt;, greater&lt;E&gt;&gt; q; // (end_time, val)
    int ans = 0;
    int cur = 0;
    for (const auto&amp; e : events) {
      while (!q.empty() &amp;&amp; q.top().first &lt; e[0]) {
        cur = max(cur, q.top().second);
        q.pop();
      }
      ans = max(ans, cur + e[2]);
      q.emplace(e[1], e[2]);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/">花花酱 LeetCode 2054. Two Best Non-Overlapping Events</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/heap/leetcode-2054-two-best-non-overlapping-events/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>LeetCode 1801. Number of Orders in the Backlog</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1801-number-of-orders-in-the-backlog/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1801-number-of-orders-in-the-backlog/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 22 Mar 2021 06:08:26 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8266</guid>

					<description><![CDATA[<p>You are given a 2D integer array&#160;orders, where each&#160;orders[i] = [pricei, amounti, orderTypei]&#160;denotes that&#160;amountiorders have been placed of type&#160;orderTypei&#160;at the price&#160;pricei. The&#160;orderTypei&#160;is: 0&#160;if it is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1801-number-of-orders-in-the-backlog/">LeetCode 1801. Number of Orders in the Backlog</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a 2D integer array&nbsp;<code>orders</code>, where each&nbsp;<code>orders[i] = [price<sub>i</sub>, amount<sub>i</sub>, orderType<sub>i</sub>]</code>&nbsp;denotes that&nbsp;<code>amount<sub>i</sub></code>orders have been placed of type&nbsp;<code>orderType<sub>i</sub></code>&nbsp;at the price&nbsp;<code>price<sub>i</sub></code>. The&nbsp;<code>orderType<sub>i</sub></code>&nbsp;is:</p>



<ul><li><code>0</code>&nbsp;if it is a batch of&nbsp;<code>buy</code>&nbsp;orders, or</li><li><code>1</code>&nbsp;if it is a batch of&nbsp;<code>sell</code>&nbsp;orders.</li></ul>



<p>Note that&nbsp;<code>orders[i]</code>&nbsp;represents a batch of&nbsp;<code>amount<sub>i</sub></code>&nbsp;independent orders with the same price and order type. All orders represented by&nbsp;<code>orders[i]</code>&nbsp;will be placed before all orders represented by&nbsp;<code>orders[i+1]</code>&nbsp;for all valid&nbsp;<code>i</code>.</p>



<p>There is a&nbsp;<strong>backlog</strong>&nbsp;that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:</p>



<ul><li>If the order is a&nbsp;<code>buy</code>&nbsp;order, you look at the&nbsp;<code>sell</code>&nbsp;order with the&nbsp;<strong>smallest</strong>&nbsp;price in the backlog. If that&nbsp;<code>sell</code>&nbsp;order&#8217;s price is&nbsp;<strong>smaller than or equal to</strong>&nbsp;the current&nbsp;<code>buy</code>&nbsp;order&#8217;s price, they will match and be executed, and that&nbsp;<code>sell</code>&nbsp;order will be removed from the backlog. Else, the&nbsp;<code>buy</code>&nbsp;order is added to the backlog.</li><li>Vice versa, if the order is a&nbsp;<code>sell</code>&nbsp;order, you look at the&nbsp;<code>buy</code>&nbsp;order with the&nbsp;<strong>largest</strong>&nbsp;price in the backlog. If that&nbsp;<code>buy</code>&nbsp;order&#8217;s price is&nbsp;<strong>larger than or equal to</strong>&nbsp;the current&nbsp;<code>sell</code>&nbsp;order&#8217;s price, they will match and be executed, and that&nbsp;<code>buy</code>&nbsp;order will be removed from the backlog. Else, the&nbsp;<code>sell</code>&nbsp;order is added to the backlog.</li></ul>



<p>Return&nbsp;<em>the total&nbsp;<strong>amount</strong>&nbsp;of orders in the backlog after placing all the orders from the input</em>. Since this number can be large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p><strong>Example 1:</strong><img alt="" src="https://assets.leetcode.com/uploads/2021/03/11/ex1.png"></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Here is what happens with the orders:
- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.
- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.
- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.
- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3<sup>rd</sup> order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4<sup>th</sup> order is added to the backlog.
Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
</pre>



<p><strong>Example 2:</strong><img alt="" src="https://assets.leetcode.com/uploads/2021/03/11/ex2.png"></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
<strong>Output:</strong> 999999984
<strong>Explanation:</strong> Here is what happens with the orders:
- 10<sup>9</sup> orders of type sell with price 7 are placed. There are no buy orders, so the 10<sup>9</sup> orders are added to the backlog.
- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.
- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.
- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.
Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (10<sup>9</sup> + 7).
</pre>



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



<ul><li><code>1 &lt;= orders.length &lt;= 10<sup>5</sup></code></li><li><code>orders[i].length == 3</code></li><li><code>1 &lt;= price<sub>i</sub>, amount<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>orderType<sub>i</sub></code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Treemap / PriorityQueue / Heap</strong></h2>



<p>buy backlog: max heap<br>sell backlog: min heap<br>Trade happens between the tops of two queues.</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 getNumberOfBacklogOrders(vector&lt;vector&lt;int&gt;&gt;&amp; orders) {  
    constexpr int kMod = 1e9 + 7;
    map&lt;int64_t, int64_t&gt; buys;
    map&lt;int64_t, int64_t&gt; sells;
    for (const auto&amp; order : orders) {      
      auto&amp; m = order[2] == 0 ? buys : sells;
      m[order[0]] += order[1];
      while (buys.size() &amp;&amp; sells.size()) {
        auto b = rbegin(buys);
        auto s = begin(sells);
        if (b-&gt;first &lt; s-&gt;first) break;
        const int k = min(b-&gt;second, s-&gt;second);
        if (!(b-&gt;second -= k)) buys.erase((++b).base());
        if (!(s-&gt;second -= k)) sells.erase(s);
      }
    }
    int64_t ans = 0;
    for (const auto&amp; [p, c] : buys) ans += c;
    for (const auto&amp; [p, c] : sells) ans += c;    
    return ans % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1801-number-of-orders-in-the-backlog/">LeetCode 1801. Number of Orders in the Backlog</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/priority-queue/leetcode-1801-number-of-orders-in-the-backlog/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1792. Maximum Average Pass Ratio</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1792-maximum-average-pass-ratio/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1792-maximum-average-pass-ratio/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Mar 2021 06:49:53 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8238</guid>

					<description><![CDATA[<p>There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array&#160;classes,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1792-maximum-average-pass-ratio/">花花酱 LeetCode 1792. Maximum Average Pass Ratio</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1792. Maximum Average Pass Ratio - 刷题找工作 EP389" width="500" height="375" src="https://www.youtube.com/embed/wZMZemdsi90?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array&nbsp;<code>classes</code>, where&nbsp;<code>classes[i] = [pass<sub>i</sub>, total<sub>i</sub>]</code>. You know beforehand that in the&nbsp;<code>i<sup>th</sup></code>&nbsp;class, there are&nbsp;<code>total<sub>i</sub></code>&nbsp;total students, but only&nbsp;<code>pass<sub>i</sub></code>&nbsp;number of students will pass the exam.</p>



<p>You are also given an integer&nbsp;<code>extraStudents</code>. There are another&nbsp;<code>extraStudents</code>&nbsp;brilliant students that are&nbsp;<strong>guaranteed</strong>&nbsp;to pass the exam of any class they are assigned to. You want to assign each of the&nbsp;<code>extraStudents</code>&nbsp;students to a class in a way that&nbsp;<strong>maximizes</strong>&nbsp;the&nbsp;<strong>average</strong>&nbsp;pass ratio across&nbsp;<strong>all</strong>&nbsp;the classes.</p>



<p>The&nbsp;<strong>pass ratio</strong>&nbsp;of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The&nbsp;<strong>average pass ratio</strong>&nbsp;is the sum of pass ratios of all the classes divided by the number of the classes.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;possible average pass ratio after assigning the&nbsp;</em><code>extraStudents</code><em>&nbsp;students.&nbsp;</em>Answers within&nbsp;<code>10<sup>-5</sup></code>&nbsp;of the actual answer will be accepted.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> classes = [[1,2],[3,5],[2,2]], <code>extraStudents</code> = 2
<strong>Output:</strong> 0.78333
<strong>Explanation:</strong> You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> classes = [[2,4],[3,9],[4,5],[2,10]], <code>extraStudents</code> = 4
<strong>Output:</strong> 0.53485
</pre>



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



<ul><li><code>1 &lt;= classes.length &lt;= 10<sup>5</sup></code></li><li><code>classes[i].length == 2</code></li><li><code>1 &lt;= pass<sub>i</sub>&nbsp;&lt;= total<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= extraStudents &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Greedy + Heap</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-1.png" alt="" class="wp-image-8241" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-2.png" alt="" class="wp-image-8242" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1792-ep389-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Sort by the ratio increase potential (p + 1) / (t + 1) &#8211; p / t.</p>



<p>Time complexity: O((m+n)logn)<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:
  double maxAverageRatio(vector&lt;vector&lt;int&gt;&gt;&amp; classes, int extraStudents) {
    const int n = classes.size();
    auto ratio = [&amp;](int i, int delta = 0) {
      return static_cast&lt;double&gt;(classes[i][0] + delta) / 
        (classes[i][1] + delta);
    };
    priority_queue&lt;pair&lt;double, int&gt;&gt; q;
    for (int i = 0; i &lt; n; ++i)
      q.emplace(ratio(i, 1) - ratio(i), i);
    while (extraStudents--) {
      const auto [r, i] = q.top(); q.pop();      
      ++classes[i][0];
      ++classes[i][1];
      q.emplace(ratio(i, 1) - ratio(i), i);
    }
    double total_ratio = 0;
    for (int i = 0; i &lt; n; ++i)
      total_ratio += ratio(i);
    return total_ratio / n;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -&gt; float:
    def ratio(i, delta=0):
      return (classes[i][0] + delta) / (classes[i][1] + delta)
    q = []
    for i, c in enumerate(classes):
      heapq.heappush(q, (-(ratio(i, 1) - ratio(i)), i))
    for _ in range(extraStudents):
      _, i = heapq.heappop(q)
      classes[i][0] += 1
      classes[i][1] += 1
      heapq.heappush(q, (-(ratio(i, 1) - ratio(i)), i))
    return mean(ratio(i) for i, _ in enumerate(classes))</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1792-maximum-average-pass-ratio/">花花酱 LeetCode 1792. Maximum Average Pass Ratio</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/priority-queue/leetcode-1792-maximum-average-pass-ratio/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1705. Maximum Number of Eaten Apples</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1705-maximum-number-of-eaten-apples/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1705-maximum-number-of-eaten-apples/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 09:17:12 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7861</guid>

					<description><![CDATA[<p>There is a special kind of apple tree that grows apples every day for&#160;n&#160;days. On the&#160;ith&#160;day, the tree grows&#160;apples[i]&#160;apples that will rot after&#160;days[i]&#160;days, that is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1705-maximum-number-of-eaten-apples/">花花酱 LeetCode 1705. Maximum Number of Eaten Apples</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a special kind of apple tree that grows apples every day for&nbsp;<code>n</code>&nbsp;days. On the&nbsp;<code>i<sup>th</sup></code>&nbsp;day, the tree grows&nbsp;<code>apples[i]</code>&nbsp;apples that will rot after&nbsp;<code>days[i]</code>&nbsp;days, that is on day&nbsp;<code>i + days[i]</code>&nbsp;the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by&nbsp;<code>apples[i] == 0</code>&nbsp;and&nbsp;<code>days[i] == 0</code>.</p>



<p>You decided to eat&nbsp;<strong>at most</strong>&nbsp;one apple a day (to keep the doctors away). Note that you can keep eating after the first&nbsp;<code>n</code>&nbsp;days.</p>



<p>Given two integer arrays&nbsp;<code>days</code>&nbsp;and&nbsp;<code>apples</code>&nbsp;of length&nbsp;<code>n</code>, return&nbsp;<em>the maximum number of apples you can eat.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> apples = [1,2,3,5,2], days = [3,2,1,4,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.
</pre>



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



<ul><li><code>apples.length == n</code></li><li><code>days.length == n</code></li><li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li><li><code>0 &lt;= apples[i], days[i] &lt;= 2 * 10<sup>4</sup></code></li><li><code>days[i] = 0</code>&nbsp;if and only if&nbsp;<code>apples[i] = 0</code>.</li></ul>



<h2><strong>Solution: PriorityQueue</strong></h2>



<p>Sort by rotten day in ascending order, only push onto the queue when that day has come (be able to grow apples).</p>



<p>Time complexity: O((n+ d)logn)<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 eatenApples(vector&lt;int&gt;&amp; apples, vector&lt;int&gt;&amp; days) {
    const int n = apples.size();
    using P = pair&lt;int, int&gt;;    
    priority_queue&lt;P, vector&lt;P&gt;, greater&lt;P&gt;&gt; q; // {rotten_day, index}    
    int ans = 0;
    for (int d = 0; d &lt; n || !q.empty(); ++d) {
      if (d &lt; n &amp;&amp; apples[d]) q.emplace(d + days[d], d);
      while (!q.empty() 
             &amp;&amp; (q.top().first &lt;= d || apples[q.top().second] == 0)) q.pop();
      if (q.empty()) continue;
      --apples[q.top().second];      
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/priority-queue/leetcode-1705-maximum-number-of-eaten-apples/">花花酱 LeetCode 1705. Maximum Number of Eaten Apples</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/priority-queue/leetcode-1705-maximum-number-of-eaten-apples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1642. Furthest Building You Can Reach</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-1642-furthest-building-you-can-reach/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-1642-furthest-building-you-can-reach/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Nov 2020 17:36:27 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7598</guid>

					<description><![CDATA[<p>You are given an integer array&#160;heights&#160;representing the heights of buildings, some&#160;bricks, and some&#160;ladders. You start your journey from building&#160;0&#160;and move to the next building by&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-1642-furthest-building-you-can-reach/">花花酱 LeetCode 1642. Furthest Building You Can Reach</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 1642. Furthest Building You Can Reach - 刷题找工作 EP366" width="500" height="281" src="https://www.youtube.com/embed/FowBaF5hYcY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an integer array&nbsp;<code>heights</code>&nbsp;representing the heights of buildings, some&nbsp;<code>bricks</code>, and some&nbsp;<code>ladders</code>.</p>



<p>You start your journey from building&nbsp;<code>0</code>&nbsp;and move to the next building by possibly using bricks or ladders.</p>



<p>While moving from building&nbsp;<code>i</code>&nbsp;to building&nbsp;<code>i+1</code>&nbsp;(<strong>0-indexed</strong>),</p>



<ul><li>If the current building&#8217;s height is&nbsp;<strong>greater than or equal</strong>&nbsp;to the next building&#8217;s height, you do&nbsp;<strong>not</strong>&nbsp;need a ladder or bricks.</li><li>If the current building&#8217;s height is&nbsp;<strong>less than</strong>&nbsp;the next building&#8217;s height, you can either use&nbsp;<strong>one ladder</strong>&nbsp;or&nbsp;<code>(h[i+1] - h[i])</code>&nbsp;<strong>bricks</strong>.</li></ul>



<p><em>Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/10/27/q4.gif" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
<strong>Output:</strong> 4
<strong>Explanation:</strong> Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 &gt;= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 &lt; 7.
- Go to building 3 without using ladders nor bricks since 7 &gt;= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 &lt; 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
<strong>Output:</strong> 7
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> heights = [14,3,19,3], bricks = 17, ladders = 0
<strong>Output:</strong> 3
</pre>



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



<ul><li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= heights[i] &lt;= 10<sup>6</sup></code></li><li><code>0 &lt;= bricks &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= ladders &lt;= heights.length</code></li></ul>



<h2><strong>Solution 0: DFS</strong></h2>



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



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



<p>AC but should be TLE</p>



<h2><strong>Solution 1: Binary Search + Greedy</strong></h2>



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



<p>Guess we can reach to m, sort the height differences from 0~m. Use ladders for larger values and use bricks for smallest values left.</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, 300 ms
class Solution {
public:
  int furthestBuilding(vector&lt;int&gt;&amp; heights, int bricks, int ladders) {
    const int n = heights.size();
    if (ladders &gt;= n - 1) return n - 1;
    vector&lt;int&gt;  diffs(n);
    for (int i = 1; i &lt; n; ++i)
      diffs[i - 1] = max(0, heights[i] - heights[i - 1]);
    int l = ladders;
    int r = n;
    while (l &lt; r) {
      int m = l + (r - l) / 2;
      vector&lt;int&gt; d(begin(diffs), begin(diffs) + m);
      nth_element(begin(d), end(d) - ladders, end(d));
      if (accumulate(begin(d), end(d) - ladders, 0) &gt; bricks)
        r = m;
      else
        l = m + 1;
    }
    return l - 1;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: 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/11/1642-ep366-3.png" alt="" class="wp-image-7603" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1642-ep366-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1642-ep366-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1642-ep366-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Use a min heap to store all the height differences ( &gt; 0) so far, if heap size is greater than ladders, which means we have to use bricks, extract the smallest value and subtract the bricks.</p>



<p>Time complexity: O(nlogk)<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, 216 ms
class Solution {
public:
  int furthestBuilding(vector&lt;int&gt;&amp; heights, int bricks, int ladders) {
    const int n = heights.size();        
    priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; q;
    for (int i = 1; i &lt; n; ++i) {
      const int d = heights[i] - heights[i - 1];
      if (d &lt;= 0) continue;
      q.push(d);
      if (q.size() &lt;= ladders) continue;
      bricks -= q.top(); q.pop();
      if (bricks &lt; 0) return i - 1;      
    }
    return n - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-1642-furthest-building-you-can-reach/">花花酱 LeetCode 1642. Furthest Building You Can Reach</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/heap/leetcode-1642-furthest-building-you-can-reach/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1606. Find Servers That Handled Most Number of Requests</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1606-find-servers-that-handled-most-number-of-requests/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1606-find-servers-that-handled-most-number-of-requests/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Oct 2020 23:43:57 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[priority_queue]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7448</guid>

					<description><![CDATA[<p>You have&#160;k&#160;servers numbered from&#160;0&#160;to&#160;k-1&#160;that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but&#160;cannot handle more than one request at&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1606-find-servers-that-handled-most-number-of-requests/">花花酱 LeetCode 1606. Find Servers That Handled Most Number of Requests</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 1606. Find Servers That Handled Most Number of Requests - 刷题找工作 EP359" width="500" height="281" src="https://www.youtube.com/embed/9OqDLNyL8Fs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You have&nbsp;<code>k</code>&nbsp;servers numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>k-1</code>&nbsp;that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but&nbsp;<strong>cannot handle more than one request at a time</strong>. The requests are assigned to servers according to a specific algorithm:</p>



<ul><li>The&nbsp;<code>i<sup>th</sup></code>&nbsp;(0-indexed) request arrives.</li><li>If all servers are busy, the request is dropped (not handled at all).</li><li>If the&nbsp;<code>(i % k)<sup>th</sup></code>&nbsp;server is available, assign the request to that server.</li><li>Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the&nbsp;<code>i<sup>th</sup></code>&nbsp;server is busy, try to assign the request to the&nbsp;<code>(i+1)<sup>th</sup></code>&nbsp;server, then the&nbsp;<code>(i+2)<sup>th</sup></code>&nbsp;server, and so on.</li></ul>



<p>You are given a&nbsp;<strong>strictly increasing</strong>&nbsp;array&nbsp;<code>arrival</code>&nbsp;of positive integers, where&nbsp;<code>arrival[i]</code>&nbsp;represents the arrival time of the&nbsp;<code>i<sup>th</sup></code>&nbsp;request, and another array&nbsp;<code>load</code>, where&nbsp;<code>load[i]</code>&nbsp;represents the load of the&nbsp;<code>i<sup>th</sup></code>&nbsp;request (the time it takes to complete). Your goal is to find the&nbsp;<strong>busiest server(s)</strong>. A server is considered&nbsp;<strong>busiest</strong>&nbsp;if it handled the most number of requests successfully among all the servers.</p>



<p>Return&nbsp;<em>a list containing the IDs (0-indexed) of the&nbsp;<strong>busiest server(s)</strong></em>. You may return the IDs in any order.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/08/load-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] 
<strong>Output:</strong> [1] 
<strong>Explanation:</strong>
All of the servers start out available.
The first 3 requests are handled by the first 3 servers in order.
Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.
Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.
Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
<strong>Output:</strong> [0]
<strong>Explanation:</strong>
The first 3 requests are handled by first 3 servers.
Request 3 comes in. It is handled by server 0 since the server is available.
Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 3, arrival = [1,2,3], load = [10,12,11]
<strong>Output:</strong> [0,1,2]
<strong>Explanation: </strong>Each server handles a single request, so they are all considered the busiest.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 3, arrival = [1,2,3,4,8,9,10], load = [5,2,10,3,1,2,2]
<strong>Output:</strong> [1]
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 1, arrival = [1], load = [1]
<strong>Output:</strong> [0]
</pre>



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



<ul><li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arrival.length, load.length &lt;= 10<sup>5</sup></code></li><li><code>arrival.length == load.length</code></li><li><code>1 &lt;= arrival[i], load[i] &lt;= 10<sup>9</sup></code></li><li><code>arrival</code>&nbsp;is&nbsp;<strong>strictly increasing</strong>.</li></ul>



<h2><strong>Solution: Heap + TreeSet</strong></h2>



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



<p>Use a min heap to store the release time -> server.<br>Use a treeset to track the current available servers.<br>For reach request, check whether servers can be released at that time.</p>



<p>Time complexity: O(nlogk)<br>Space complexity: 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:
  vector&lt;int&gt; busiestServers(int k, vector&lt;int&gt;&amp; arrival, vector&lt;int&gt;&amp; load) {
    priority_queue&lt;pair&lt;int, int&gt;, vector&lt;pair&lt;int,int&gt;&gt;, greater&lt;&gt;&gt; q; // {release_time, server}
    set&lt;int&gt; servers;
    vector&lt;int&gt; requests(k);
    
    for (int i = 0; i &lt; k; ++i)
      servers.insert(i);
    
    for (int i = 0; i &lt; arrival.size(); ++i) {
      const int t = arrival[i];
      const int l = load[i];
      
      // Release servers. O(logk) per pop()
      while (!q.empty() &amp;&amp; q.top().first &lt;= t) {        
        servers.insert(q.top().second);  
        q.pop();
      }
      
      // Drop the request.
      if (servers.empty()) continue;
      
      // Find first avaiable one O(logk)
      auto it = servers.lower_bound(i % k);
      if (it == servers.end()) it = begin(servers);
      const int idx = *it;
      
      ++requests[idx];
      servers.erase(it);
      q.emplace(t + l, idx);
    }
    const int max_req = *max_element(begin(requests), end(requests));
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; k; ++i)
      if (requests[i] == max_req) ans.push_back(i);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1606-find-servers-that-handled-most-number-of-requests/">花花酱 LeetCode 1606. Find Servers That Handled Most Number of Requests</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/simulation/leetcode-1606-find-servers-that-handled-most-number-of-requests/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1488. Avoid Flood in The City</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1488-avoid-flood-in-the-city/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1488-avoid-flood-in-the-city/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Jun 2020 06:18:33 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6959</guid>

					<description><![CDATA[<p>Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the&#160;nth&#160;lake, the&#160;nth&#160;lake becomes full of water.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1488-avoid-flood-in-the-city/">花花酱 LeetCode 1488. Avoid Flood in The City</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the&nbsp;<code>nth</code>&nbsp;lake, the&nbsp;<code>nth</code>&nbsp;lake becomes full of water. If it rains over a lake which is&nbsp;<strong>full of water</strong>, there will be a&nbsp;<strong>flood</strong>. Your goal is to avoid the flood in any lake.</p>



<p>Given an integer array&nbsp;<code>rains</code>&nbsp;where:</p>



<ul><li><code>rains[i] &gt; 0</code>&nbsp;means there will be rains over the&nbsp;<code>rains[i]</code>&nbsp;lake.</li><li><code>rains[i] == 0</code>&nbsp;means there are no rains this day and you can choose&nbsp;<strong>one lake</strong>&nbsp;this day and&nbsp;<strong>dry it</strong>.</li></ul>



<p>Return&nbsp;<em>an array&nbsp;<code>ans</code></em>&nbsp;where:</p>



<ul><li><code>ans.length == rains.length</code></li><li><code>ans[i] == -1</code>&nbsp;if&nbsp;<code>rains[i] &gt; 0</code>.</li><li><code>ans[i]</code>&nbsp;is the lake you choose to dry in the&nbsp;<code>ith</code>&nbsp;day&nbsp;if&nbsp;<code>rains[i] == 0</code>.</li></ul>



<p>If there are multiple valid answers return&nbsp;<strong>any</strong>&nbsp;of them. If it is impossible to avoid flood return&nbsp;<strong>an empty array</strong>.</p>



<p>Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rains = [1,2,3,4]
<strong>Output:</strong> [-1,-1,-1,-1]
<strong>Explanation:</strong> After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rains = [1,2,0,0,2,1]
<strong>Output:</strong> [-1,-1,2,1,-1,-1]
<strong>Explanation:</strong> After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rains = [1,2,0,1,2]
<strong>Output:</strong> []
<strong>Explanation:</strong> After the second day, full lakes are  [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rains = [69,0,0,0,69]
<strong>Output:</strong> [-1,69,1,1,-1]
<strong>Explanation:</strong> Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1] is acceptable where 1 &lt;= x,y &lt;= 10^9
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rains = [10,20,20]
<strong>Output:</strong> []
<strong>Explanation:</strong> It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
</pre>



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



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



<h2><strong>Solution: Binary Search</strong></h2>



<p>Store the days we can dry a lake in a treeset.<br>Store the last day when a lake becomes full in a hashtable.<br>Whenever we encounter a full lake, try to find the first available day that we can dry it. If no such day, return no answer.</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:
  vector&lt;int&gt; avoidFlood(vector&lt;int&gt;&amp; rains) {   
    const int n = rains.size();
    vector&lt;int&gt; ans(n, -1);
    unordered_map&lt;int, int&gt; full; // lake -&gt; day
    set&lt;int&gt; dry; // days we can dry lakes.
    for (int i = 0; i &lt; n; ++i) {
      const int lake = rains[i];
      if (lake &gt; 0) {
        if (full.count(lake)) {
          // Find the first day we can dry it.
          auto it = dry.upper_bound(full[lake]);
          if (it == end(dry)) return {};
          ans[*it] = lake;
          dry.erase(it);
        }
        full[lake] = i;
      } else {
        dry.insert(i);
        ans[i] = 1;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1488-avoid-flood-in-the-city/">花花酱 LeetCode 1488. Avoid Flood in The City</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/algorithms/binary-search/leetcode-1488-avoid-flood-in-the-city/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1094. Car Pooling</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-1094-car-pooling/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-1094-car-pooling/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Jun 2019 04:32:35 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5241</guid>

					<description><![CDATA[<p>You are driving a vehicle that&#160;has&#160;capacity&#160;empty seats initially available for passengers.&#160; The vehicle&#160;only&#160;drives east (ie. it&#160;cannot&#160;turn around and drive west.) Given a list of&#160;trips,&#160;trip[i] =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-1094-car-pooling/">花花酱 LeetCode 1094. Car Pooling</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are driving a vehicle that&nbsp;has&nbsp;<code>capacity</code>&nbsp;empty seats initially available for passengers.&nbsp; The vehicle&nbsp;<strong>only</strong>&nbsp;drives east (ie. it&nbsp;<strong>cannot</strong>&nbsp;turn around and drive west.)</p>



<p>Given a list of&nbsp;<code>trips</code>,&nbsp;<code>trip[i] = [num_passengers, start_location, end_location]</code>&nbsp;contains information about the&nbsp;<code>i</code>-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off.&nbsp; The locations are given as the number of kilometers&nbsp;due east from your vehicle&#8217;s initial location.</p>



<p>Return&nbsp;<code>true</code>&nbsp;if and only if&nbsp;it is possible to pick up and drop off all passengers for all the given trips.&nbsp;</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>trips = [[2,1,5],[3,3,7]], capacity = 4
<strong>Output: </strong>false
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>trips = [[2,1,5],[3,3,7]], capacity = 5
<strong>Output: </strong>true
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>trips = [[2,1,5],[3,5,7]], capacity = 3
<strong>Output: </strong>true
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input: </strong>trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
<strong>Output: </strong>true</pre>



<h2><strong>Solution1: Min heap</strong></h2>



<p>Sort events by location</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:
  bool carPooling(vector&lt;vector&lt;int&gt;&gt;&amp; trips, int capacity) {
    priority_queue&lt;int&gt; q;
    for (const auto&amp; trip : trips) {
      int pick_up = -((trip[1] &lt;&lt; 10) | (1 &lt;&lt; 9) | trip[0]);
      int drop_off = -((trip[2] &lt;&lt; 10) | trip[0]);
      q.push(pick_up);
      q.push(drop_off);
    }
    while (q.size()) {
      int key = -q.top(); q.pop();
      int sign = ((key &gt;&gt; 9) &amp; 1) ? 1: -1;
      int num = key &amp; 0xFF;
      if ((capacity -= sign * num) &lt; 0)
        return false;
    }
    return true;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Preprocessing</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool carPooling(vector&lt;vector&lt;int&gt;&gt;&amp; trips, int capacity) {
    vector&lt;int&gt; d(1001);
    for (const auto&amp; trip : trips) {
      d[trip[1]] -= trip[0];
      d[trip[2]] += trip[0];
    }
    for (const int c : d) 
      if ((capacity += c) &lt; 0) return false;
    return true;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-1094-car-pooling/">花花酱 LeetCode 1094. Car Pooling</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/heap/leetcode-1094-car-pooling/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 23. Merge k Sorted Lists</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 08:02:55 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[merge]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4117</guid>

					<description><![CDATA[<p>Problem Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [   1-&#62;4-&#62;5,   1-&#62;3-&#62;4,   2-&#62;6&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/">花花酱 LeetCode 23. Merge k Sorted Lists</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>Merge <em>k</em> sorted linked lists and return it as one sorted list. Analyze and describe its complexity.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>
[
  1-&gt;4-&gt;5,
  1-&gt;3-&gt;4,
  2-&gt;6
]
<strong>Output:</strong> 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6</pre>
<h1><strong>Solution 1: Brute Force</strong></h1>
<p>Time complexity: O(nk)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 420 ms
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    ListNode dummy(0);
    ListNode *cur = &amp;dummy;
    while (true) {
      ListNode** min_head = nullptr;
      for (auto&amp; head : lists) {          
        if (!head) continue;        
        if (!min_head || head-&gt;val &lt; (*min_head)-&gt;val)
          min_head = &amp;head;
      }
      if (!min_head) break;
      cur-&gt;next = new ListNode((*min_head)-&gt;val);
      cur = cur-&gt;next;
      *min_head = (*min_head)-&gt;next;      
    }
    return dummy.next;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Heap / Priority Queue</strong></h1>
<p>Time complexity: O(nlogk)</p>
<p>Space complexity: O(k)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms (&lt;99.88%)
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    ListNode dummy(0);
    ListNode *cur = &amp;dummy;
    
    auto comp = [](ListNode* a, ListNode* b) { return a-&gt;val &gt; b-&gt;val; };
    priority_queue&lt;ListNode*, vector&lt;ListNode*&gt;, decltype(comp)&gt; q(comp);
    
    for (ListNode* list : lists) 
      if (list) q.push(list);
    
    while (!q.empty()) {
      cur-&gt;next = q.top(); q.pop();      
      cur = cur-&gt;next;
      if (cur-&gt;next) q.push(cur-&gt;next);
    }
    return dummy.next;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/">花花酱 LeetCode 23. Merge k Sorted Lists</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/list/leetcode-23-merge-k-sorted-lists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 628. Maximum Product of Three Numbers</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Aug 2018 05:02:31 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[priority_queue]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[topk]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3594</guid>

					<description><![CDATA[<p>Problem Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/">花花酱 LeetCode 628. Maximum Product of Three Numbers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/_ID-lcUd_vg?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1>Problem</h1>
<p>Given an integer array, find three numbers whose product is maximum and output the maximum product.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,2,3]
<b>Output:</b> 6
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false "><b>Input:</b> [1,2,3,4]
<b>Output:</b> 24
</pre>
<p><b>Note:</b></p>
<ol>
<li>The length of the given array will be in range [3,10<sup>4</sup>] and all elements are in the range [-1000, 1000].</li>
<li>Multiplication of any three numbers in the input won&#8217;t exceed the range of 32-bit signed integer.</li>
</ol>
<h1>Idea:</h1>
<p>Find the top 3 numbers t1, t2, t3, and bottom 2 numbers, b1, b2.</p>
<p>If all numbers are positives,  answer must be t1 * t2 * t3.</p>
<p>Since the number can go negative, the answer must be either t1*t2*t3 or b1 * b2 * t1, if b1 and b2 are both negatives.</p>
<p>ex. nums: [5, 1, -6, 3, -1]</p>
<p>t1, t2, t3: 5, 3, 1</p>
<p>b1, b2: -6, -1</p>
<p>t1 * t2 * t3 = 15</p>
<p>t1 * b1 * b2 = 30</p>
<h1><strong>Solution 1: Manual Tracking</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
public:
  int maximumProduct(vector&lt;int&gt;&amp; nums) {
    int max1 = INT_MIN;
    int max2 = INT_MIN;
    int max3 = INT_MIN;
    int min1 = INT_MAX;
    int min2 = INT_MAX;

    for (const int num: nums) {
      if (num &gt; max1) {
          max3 = max2;
          max2 = max1;
          max1 = num;
      } else if (num &gt; max2) {
          max3 = max2;
          max2 = num;
      } else if (num &gt; max3) {
          max3=num;
      }

      if (num &lt; min1) {
          min2 = min1;
          min1 = num;
      } else if (num &lt; min2) {
          min2=num;
      }
    }

    return max(max1*max2*max3, max1*min1*min2);
  }
};</pre><p></p>
<h1><strong>Solution 2: Sorting</strong></h1>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 48 ms
class Solution {
public:
  int maximumProduct(vector&lt;int&gt;&amp; nums) {
    int n = nums.size();
    sort(nums.rbegin(), nums.rend());
    return max(nums[0] * nums[1] * nums[2], nums[0] * nums[n - 1] * nums[n - 2]);
  }
};</pre><p></p>
<h1><strong>Solution 3: Two Heaps (Priority Queues)</strong></h1>
<p>Time complexity: O(nlog3)</p>
<p>Space complexity: O(2 + 3)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 40 ms
class Solution {
public:
  int maximumProduct(vector&lt;int&gt;&amp; nums) {
    priority_queue&lt;int, vector&lt;int&gt;, less&lt;int&gt;&gt; min_q; // max_heap
    priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; max_q; // min_heap
    
    for (int num : nums) {
      max_q.push(num);
      if (max_q.size() &gt; 3) max_q.pop();
      min_q.push(num);
      if (min_q.size() &gt; 2) min_q.pop();
    }
    
    int max3 = max_q.top(); max_q.pop();
    int max2 = max_q.top(); max_q.pop();
    int max1 = max_q.top(); max_q.pop();
    int min2 = min_q.top(); min_q.pop();
    int min1 = min_q.top(); min_q.pop();
    
    return max(max1 * max2 * max3, max1 * min1 * min2); 
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/">花花酱 LeetCode 628. Maximum Product of Three Numbers</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/math/leetcode-628-maximum-product-of-three-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 703. Kth Largest Element in a Stream</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 03:33:59 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[stream]]></category>
		<category><![CDATA[top k]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3095</guid>

					<description><![CDATA[<p>Problem Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/">花花酱 LeetCode 703. Kth Largest Element in a Stream</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>Design a class to find the <strong>k</strong>th largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.</p>
<p>Your <code>KthLargest</code> class will have a constructor which accepts an integer <code>k</code> and an integer array <code>nums</code>, which contains initial elements from the stream. For each call to the method <code>KthLargest.add</code>, return the element representing the kth largest element in the stream.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false">int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3);   // returns 4
kthLargest.add(5);   // returns 5
kthLargest.add(10);  // returns 5
kthLargest.add(9);   // returns 8
kthLargest.add(4);   // returns 8
</pre>
<p><strong>Note: </strong><br />
You may assume that <code>nums</code>&#8216; length ≥ <code>k-1</code> and <code>k</code> ≥ 1.</p>
<h1><strong>Solution: BST / Min Heap</strong></h1>
<p>Time complexity: O(nlogk)</p>
<p>Space complexity: O(k)</p>
<p>C++ / BST</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
class KthLargest {
public:
  KthLargest(int k, vector&lt;int&gt; nums): k_(k) {
    for (int num : nums)
      add(num);
  }

  int add(int val) {    
    s_.insert(val);
    if (s_.size() &gt; k_)
      s_.erase(s_.begin());
    return *s_.begin();
  }
private:
  const int k_;  
  multiset&lt;int&gt; s_;
};</pre><p>C++ / Min Heap</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class KthLargest {
public:
  KthLargest(int k, vector&lt;int&gt; nums): k_(k) {    
    for (int num : nums)
      add(num);
  }

  int add(int val) {    
    s_.push(val);
    if (s_.size() &gt; k_)
      s_.pop();
    return s_.top();
  }
private:
  const int k_;  
  priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; s_; // min heap
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/">花花酱 LeetCode 703. Kth Largest Element in a Stream</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/heap/leetcode-703-kth-largest-element-in-a-stream/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
