<?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 &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/priority-queue/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 28 Mar 2025 03:46:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Priority Queue &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3408. Design Task Manager</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Mar 2025 03:45:03 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10229</guid>

					<description><![CDATA[pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId m_ 使用std::unordered_map，存储taskId -> pq_的迭代器 所有操作都是O(logn) [crayon-67eaa981220c5696701222/]]]></description>
										<content:encoded><![CDATA[
<ol class="wp-block-list"><li>pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId</li><li>m_ 使用std::unordered_map，存储taskId -> pq_的迭代器</li></ol>



<p>所有操作都是O(logn)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class TaskManager {
public:
    TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks) {
      for (const auto&amp; task : tasks)
        add(task[0], task[1], task[2]);
    }

    void add(int userId, int taskId, int priority) {
      m_[taskId] = pq_.emplace(make_pair(priority, taskId), userId).first;
    }
    
    void edit(int taskId, int newPriority) {
      const int userId = m_[taskId]-&gt;second;
      rmv(taskId);
      add(userId, taskId, newPriority);
    }
    
    void rmv(int taskId) {
      auto it = m_.find(taskId);
      pq_.erase(it-&gt;second);
      m_.erase(it);
    }
    
    int execTop() {
      if (pq_.empty()) return -1;
      auto it = pq_.rbegin();
      const int userId = it-&gt;second;
      const int taskId = (it-&gt;first.second);
      rmv(taskId);
      return userId;
    }
  private:
    map&lt;std::pair&lt;int,int&gt;, int&gt; pq_; // (priority, taskId) -&gt; userId;
    unordered_map&lt;int, map&lt;std::pair&lt;int,int&gt;, int&gt;::iterator&gt; m_; // taskId -&gt; pq iterator
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2233. Maximum Product After K Increments</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Apr 2022 06:38:03 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[product]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9640</guid>

					<description><![CDATA[You are given an array of non-negative integers&#160;nums&#160;and an integer&#160;k. In one operation, you may choose&#160;any&#160;element from&#160;nums&#160;and&#160;increment&#160;it by&#160;1. Return&#160;the&#160;maximum&#160;product&#160;of&#160;nums&#160;after&#160;at most&#160;k&#160;operations.&#160;Since the answer may be very&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of non-negative integers&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. In one operation, you may choose&nbsp;<strong>any</strong>&nbsp;element from&nbsp;<code>nums</code>&nbsp;and&nbsp;<strong>increment</strong>&nbsp;it by&nbsp;<code>1</code>.</p>



<p>Return<em>&nbsp;the&nbsp;<strong>maximum</strong>&nbsp;<strong>product</strong>&nbsp;of&nbsp;</em><code>nums</code><em>&nbsp;after&nbsp;<strong>at most</strong>&nbsp;</em><code>k</code><em>&nbsp;operations.&nbsp;</em>Since the answer may be very large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,4], k = 5
<strong>Output:</strong> 20
<strong>Explanation:</strong> Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [6,3,3,2], k = 2
<strong>Output:</strong> 216
<strong>Explanation:</strong> Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length, k &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: priority queue</strong></h2>



<p>Always increment the smallest number. Proof?</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumProduct(vector&lt;int&gt;&amp; nums, int k) {
    constexpr int kMod = 1e9 + 7;
    priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; q(begin(nums), end(nums));
    while (k--) {
      const int n = q.top(); 
      q.pop();
      q.push(n + 1);
    }
    long long ans = 1;
    while (!q.empty()) {
      ans *= q.top(); q.pop();
      ans %= kMod;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/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[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;]]></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 class="wp-block-list"><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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 1851. Minimum Interval to Include Each Query</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1851-minimum-interval-to-include-each-query/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1851-minimum-interval-to-include-each-query/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 May 2021 06:05:19 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8439</guid>

					<description><![CDATA[You are given a 2D integer array&#160;intervals, where&#160;intervals[i] = [lefti, righti]&#160;describes the&#160;ith&#160;interval starting at&#160;lefti&#160;and ending at&#160;righti&#160;(inclusive). The&#160;size&#160;of an interval is defined as the number of&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a 2D integer array&nbsp;<code>intervals</code>, where&nbsp;<code>intervals[i] = [left<sub>i</sub>, right<sub>i</sub>]</code>&nbsp;describes the&nbsp;<code>i<sup>th</sup></code>&nbsp;interval starting at&nbsp;<code>left<sub>i</sub></code>&nbsp;and ending at&nbsp;<code>right<sub>i</sub></code>&nbsp;<strong>(inclusive)</strong>. The&nbsp;<strong>size</strong>&nbsp;of an interval is defined as the number of integers it contains, or more formally&nbsp;<code>right<sub>i</sub>&nbsp;- left<sub>i</sub>&nbsp;+ 1</code>.</p>



<p>You are also given an integer array&nbsp;<code>queries</code>. The answer to the&nbsp;<code>j<sup>th</sup></code>&nbsp;query is the&nbsp;<strong>size of the smallest interval</strong>&nbsp;<code>i</code>&nbsp;such that&nbsp;<code>left<sub>i</sub>&nbsp;&lt;= queries[j] &lt;= right<sub>i</sub></code>. If no such interval exists, the answer is&nbsp;<code>-1</code>.</p>



<p>Return&nbsp;<em>an array containing the answers to the queries</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
<strong>Output:</strong> [3,3,1,4]
<strong>Explanation:</strong> The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
<strong>Output:</strong> [2,-1,4,6]
<strong>Explanation:</strong> The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li><li><code>intervals[i].length == 2</code></li><li><code>1 &lt;= left<sub>i</sub>&nbsp;&lt;= right<sub>i</sub>&nbsp;&lt;= 10<sup>7</sup></code></li><li><code>1 &lt;= queries[j] &lt;= 10<sup>7</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Offline Processing</strong> <strong>+ Priority Queue</strong></h2>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1847-closest-room/" data-type="post" data-id="8419">花花酱 LeetCode 1847. Closest Room</a></p>



<p>Sort intervals by right in descending order, sort queries in descending. Add valid intervals into the priority queue (or treeset) ordered by size in ascending order. Erase invalid ones. The first one (if any) will be the one with the smallest size that contains the current query.</p>



<p>Time complexity: O(nlogn + mlogm + mlogn)<br>Space complexity: O(m + n)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; minInterval(vector&lt;vector&lt;int&gt;&gt;&amp; intervals, vector&lt;int&gt;&amp; queries) {
    const int n = intervals.size();
    const int m = queries.size();    
    sort(begin(intervals), end(intervals), [](const auto&amp; a, const auto&amp; b){
      return a[1] &gt; b[1];
    });
    vector&lt;pair&lt;int, int&gt;&gt; qs(m); // {query, i}
    for (int i = 0; i &lt; m; ++i)
      qs[i] = {queries[i], i};
    sort(rbegin(qs), rend(qs));

    vector&lt;int&gt; ans(m);
    int j = 0;
    priority_queue&lt;pair&lt;int, int&gt;&gt; pq; // {-size, left}
    for (const auto&amp; [query, i] : qs) {
      while (j &lt; n &amp;&amp; intervals[j][1] &gt;= query) {
        pq.emplace(-(intervals[j][1] - intervals[j][0] + 1),
                   intervals[j][0]);
        ++j;
      }
      while (!pq.empty() &amp;&amp; pq.top().second &gt; query) 
        pq.pop();      
      ans[i] = pq.empty() ? -1 : -pq.top().first;         
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1851-minimum-interval-to-include-each-query/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[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;]]></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 class="wp-block-list"><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 class="wp-block-list"><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 decoding="async" 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 decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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[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;]]></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="281" src="https://www.youtube.com/embed/wZMZemdsi90?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" 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 class="wp-block-list"><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 class="wp-block-heading"><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 fetchpriority="high" decoding="async" 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 decoding="async" 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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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>
]]></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[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;]]></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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 1675. Minimize Deviation in Array</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1675-minimize-deviation-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1675-minimize-deviation-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Nov 2020 21:54:59 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[operation]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7743</guid>

					<description><![CDATA[You are given an array&#160;nums&#160;of&#160;n&#160;positive integers. You can perform two types of operations on any element of the array any number of times: If the&#8230;]]></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 loading="lazy" title="花花酱 LeetCode 1675. Minimize Deviation in Array - 刷题找工作 EP372" width="500" height="281" src="https://www.youtube.com/embed/l_o4fp6BHYY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>nums</code>&nbsp;of&nbsp;<code>n</code>&nbsp;positive integers.</p>



<p>You can perform two types of operations on any element of the array any number of times:</p>



<ul class="wp-block-list"><li>If the element is&nbsp;<strong>even</strong>,&nbsp;<strong>divide</strong>&nbsp;it by&nbsp;<code>2</code>.<ul><li>For example, if the array is&nbsp;<code>[1,2,3,4]</code>, then you can do this operation on the last element, and the array will be&nbsp;<code>[1,2,3,2].</code></li></ul></li><li>If the element is&nbsp;<strong>odd</strong>,&nbsp;<strong>multiply</strong>&nbsp;it by&nbsp;<code>2</code>.<ul><li>For example, if the array is&nbsp;<code>[1,2,3,4]</code>, then you can do this operation on the first element, and the array will be&nbsp;<code>[2,2,3,4].</code></li></ul></li></ul>



<p>The&nbsp;<strong>deviation</strong>&nbsp;of the array is the&nbsp;<strong>maximum difference</strong>&nbsp;between any two elements in the array.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum deviation</strong>&nbsp;the array can have after performing some number of operations.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,1,5,20,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
</pre>



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



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



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



<ul class="wp-block-list"><li><code>n == nums.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Priority Queue</strong></h2>



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



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



<p>If we double an odd number it becomes an even number, then we can only divide it by two which gives us back the original number. So we can pre-double all the odd numbers and only do division in the following process. </p>



<p>We push all numbers including pre-doubled odd ones onto a priority queue, and track the difference between the largest and smallest number.</p>



<p>Each time, we pop the largest number out and divide it by two then put it back to the priority queue, until the largest number becomes odd. We can not discard it and divide any other smaller numbers by two will only increase the max difference, so we can stop here.</p>



<p>ex1: [3, 5, 8] =&gt; [6, 8, 10] (pre-double) =&gt; [5, 6, 8] =&gt; [4, 5, 6] =&gt; [3, 4, 5] max diff is 5 &#8211; 3 = 2<br>ex2: [4,1,5,20,3] =&gt; [2, 4, 6, 10, 20] (pre-double) =&gt; [2, 4, 6, 10] =&gt; [2, 4, 5, 6] =&gt; [2,3,4,5] max diff = 5-2 = 3</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minimumDeviation(vector&lt;int&gt;&amp; nums) {
    set&lt;int&gt; s;
    for (int x : nums)
      s.insert(x &amp; 1 ? x * 2 : x);
    int ans = *rbegin(s) - *begin(s);
    while (*rbegin(s) % 2 == 0) {
      s.insert(*rbegin(s) / 2);
      s.erase(*rbegin(s));
      ans = min(ans, *rbegin(s) - *begin(s));
    }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">C++/PQ</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minimumDeviation(vector&lt;int&gt;&amp; nums) {
    priority_queue&lt;int&gt; q;    
    int lo = INT_MAX;
    for (int x : nums) {
      x = x &amp; 1 ? x * 2 : x;
      q.push(x);
      lo = min(lo, x);
    }
    int ans = q.top() - lo;
    while (q.top() % 2 == 0) {
      int x = q.top(); q.pop();
      q.push(x / 2);
      lo = min(lo, x / 2);
      ans = min(ans, q.top() - lo);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-1675-minimize-deviation-in-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
