<?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>priority_queue Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/priority_queue/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/priority_queue/</link>
	<description></description>
	<lastBuildDate>Mon, 21 Mar 2022 12:41:37 +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>priority_queue Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/priority_queue/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 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 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>
	</channel>
</rss>
