<?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>sorting Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/sorting/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/sorting/</link>
	<description></description>
	<lastBuildDate>Sun, 05 Mar 2023 15:52:24 +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>sorting Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/sorting/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Mar 2023 15:51:10 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9973</guid>

					<description><![CDATA[<p>You are given the&#160;root&#160;of a binary tree and a positive integer&#160;k. The&#160;level sum&#160;in the tree is the sum of the values of the nodes that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</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 the&nbsp;<code>root</code>&nbsp;of a binary tree and a positive integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>level sum</strong>&nbsp;in the tree is the sum of the values of the nodes that are on the&nbsp;<strong>same</strong>&nbsp;level.</p>



<p>Return<em>&nbsp;the&nbsp;</em><code>k<sup>th</sup></code><em>&nbsp;<strong>largest</strong>&nbsp;level sum in the tree (not necessarily distinct)</em>. If there are fewer than&nbsp;<code>k</code>&nbsp;levels in the tree, return&nbsp;<code>-1</code>.</p>



<p><strong>Note</strong>&nbsp;that two nodes are on the same level if they have the same distance from the root.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/12/14/binaryytreeedrawio-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/12/14/treedrawio-3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>



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



<ul><li>The number of nodes in the tree is&nbsp;<code>n</code>.</li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li><code>1 &lt;= k &lt;= n</code></li></ul>



<h2><strong>Solution: DFS + Sorting</strong></h2>



<p>Use DFS to traverse the tree and accumulate level sum. Once done, sort the level sums and find the k-th largest one.</p>



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



<p>Note: sum can be very large, use long long.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long kthLargestLevelSum(TreeNode* root, int k) {
    vector&lt;long long&gt; sums;
    function&lt;void(TreeNode*, int)&gt; dfs = [&amp;](TreeNode* root, int d) {
      if (!root) return;
      while (d &gt;= sums.size()) sums.push_back(0);
      sums[d] += root-&gt;val;
      dfs(root-&gt;left, d + 1);
      dfs(root-&gt;right, d + 1);
    };
    dfs(root, 0);
    if (sums.size() &lt; k) return -1;
    sort(rbegin(sums), rend(sums));
    return sums[k - 1];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</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/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2231. Largest Number After Digit Swaps by Parity</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2231-largest-number-after-digit-swaps-by-parity/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2231-largest-number-after-digit-swaps-by-parity/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Apr 2022 06:03:37 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[generation]]></category>
		<category><![CDATA[largest]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9633</guid>

					<description><![CDATA[<p>You are given a positive integer&#160;num. You may swap any two digits of&#160;num&#160;that have the same&#160;parity&#160;(i.e. both odd digits or both even digits). Return&#160;the&#160;largest&#160;possible value&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2231-largest-number-after-digit-swaps-by-parity/">花花酱 LeetCode 2231. Largest Number After Digit Swaps by Parity</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 positive integer&nbsp;<code>num</code>. You may swap any two digits of&nbsp;<code>num</code>&nbsp;that have the same&nbsp;<strong>parity</strong>&nbsp;(i.e. both odd digits or both even digits).</p>



<p>Return<em>&nbsp;the&nbsp;<strong>largest</strong>&nbsp;possible value of&nbsp;</em><code>num</code><em>&nbsp;after&nbsp;<strong>any</strong>&nbsp;number of swaps.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 1234
<strong>Output:</strong> 3412
<strong>Explanation:</strong> Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 65875
<strong>Output:</strong> 87655
<strong>Explanation:</strong> Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
</pre>



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



<ul><li><code>1 &lt;= num &lt;= 10<sup>9</sup></code></li></ul>



<p>Solution:</p>



<p>Put all even digits into one array, all odd digits into another one, all digits into the third. Sort two arrays, and generate a new number from sorted arrays.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int largestInteger(int num) {
    vector&lt;int&gt; odd, even, org;
    for (int cur = num; cur; cur /= 10) {
      ((cur &amp; 1) ? odd : even).push_back(cur % 10);
      org.push_back(cur % 10);
    }
    sort(begin(odd), end(odd));
    sort(begin(even), end(even));    
    int ans = 0;
    for (int i = 0; i &lt; org.size(); ++i) {
      if (i) ans *= 10;
      auto&amp; cur = (org[org.size() - i - 1] &amp; 1) ? odd : even;
      ans += cur.back();
      cur.pop_back();
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2231-largest-number-after-digit-swaps-by-parity/">花花酱 LeetCode 2231. Largest Number After Digit Swaps by Parity</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/array/leetcode-2231-largest-number-after-digit-swaps-by-parity/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2195. Append K Integers With Minimal Sum</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 08 Mar 2022 11:25:58 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9550</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;and an integer&#160;k. Append&#160;k&#160;unique positive&#160;integers that do&#160;not&#160;appear in&#160;nums&#160;to&#160;nums&#160;such that the resulting total sum is&#160;minimum. Return&#160;the sum of the&#160;k&#160;integers appended to&#160;nums.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/">花花酱 LeetCode 2195. Append K Integers With Minimal 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 integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. Append&nbsp;<code>k</code>&nbsp;<strong>unique positive</strong>&nbsp;integers that do&nbsp;<strong>not</strong>&nbsp;appear in&nbsp;<code>nums</code>&nbsp;to&nbsp;<code>nums</code>&nbsp;such that the resulting total sum is&nbsp;<strong>minimum</strong>.</p>



<p>Return<em>&nbsp;the sum of the</em>&nbsp;<code>k</code>&nbsp;<em>integers appended to</em>&nbsp;<code>nums</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,25,10,25], k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> The two unique positive integers that do not appear in nums which we append are 2 and 3.
The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.
The sum of the two integers appended is 2 + 3 = 5, so we return 5.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,6], k = 6
<strong>Output:</strong> 25
<strong>Explanation:</strong> The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.
The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. 
The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.
</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>9</sup></code></li><li><code>1 &lt;= k &lt;= 10<sup>8</sup></code></li></ul>



<h2><strong>Solution: Greedy + Math, fill the gap</strong></h2>



<p>Sort all the numbers and remove duplicated ones, and fill the gap between two neighboring numbers.<br>e.g. [15, 3, 8, 8] => sorted = [3, 8, 15] <br>fill 0->3, 1,2, sum = ((0 + 1) + (3-1)) * (3-0-1) / 2 = 3<br>fill 3->8, 4, 5, 6, 7, <meta charset="utf-8">sum = ((3 + 1) + (8-1)) * (8-3-1) / 2 = 22<br>fill 8->15, 9, 10, &#8230;, 14, &#8230;<br>fill 15->inf, 16, 17, &#8230;</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimalKSum(vector&lt;int&gt;&amp; nums, int k) {    
    sort(begin(nums), end(nums));
    long long ans = 0;
    long long p = 0;
    for (int c : nums) {
      if (c == p) continue;
      long long n = min((long long)k, c - p - 1);
      ans += (p + 1 + p + n) * n / 2; 
      k -= n;
      p = c;
    }
    ans += (p + 1 + p + k) * k / 2;
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/">花花酱 LeetCode 2195. Append K Integers With Minimal 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/greedy/leetcode-2195-append-k-integers-with-minimal-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2146. K Highest Ranked Items Within a Price Range</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 04 Feb 2022 01:23:04 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9458</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;2D integer array&#160;grid&#160;of size&#160;m x n&#160;that represents a map of the items in a shop. The integers in the grid represent the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/">花花酱 LeetCode 2146. K Highest Ranked Items Within a Price Range</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&nbsp;<code>grid</code>&nbsp;of size&nbsp;<code>m x n</code>&nbsp;that represents a map of the items in a shop. The integers in the grid represent the following:</p>



<ul><li><code>0</code>&nbsp;represents a wall that you cannot pass through.</li><li><code>1</code>&nbsp;represents an empty cell that you can freely move to and from.</li><li>All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.</li></ul>



<p>It takes&nbsp;<code>1</code>&nbsp;step to travel between adjacent grid cells.</p>



<p>You are also given integer arrays&nbsp;<code>pricing</code>&nbsp;and&nbsp;<code>start</code>&nbsp;where&nbsp;<code>pricing = [low, high]</code>&nbsp;and&nbsp;<code>start = [row, col]</code>&nbsp;indicates that you start at the position&nbsp;<code>(row, col)</code>&nbsp;and are interested only in items with a price in the range of&nbsp;<code>[low, high]</code>&nbsp;(<strong>inclusive</strong>). You are further given an integer&nbsp;<code>k</code>.</p>



<p>You are interested in the&nbsp;<strong>positions</strong>&nbsp;of the&nbsp;<code>k</code>&nbsp;<strong>highest-ranked</strong>&nbsp;items whose prices are&nbsp;<strong>within</strong>&nbsp;the given price range. The rank is determined by the&nbsp;<strong>first</strong>&nbsp;of these criteria that is different:</p>



<ol><li>Distance, defined as the length of the shortest path from the&nbsp;<code>start</code>&nbsp;(<strong>shorter</strong>&nbsp;distance has a higher rank).</li><li>Price (<strong>lower</strong>&nbsp;price has a higher rank, but it must be&nbsp;<strong>in the price range</strong>).</li><li>The row number (<strong>smaller</strong>&nbsp;row number has a higher rank).</li><li>The column number (<strong>smaller</strong>&nbsp;column number has a higher rank).</li></ol>



<p>Return&nbsp;<em>the&nbsp;</em><code>k</code><em>&nbsp;highest-ranked items within the price range&nbsp;<strong>sorted</strong>&nbsp;by their rank (highest to lowest)</em>. If there are fewer than&nbsp;<code>k</code>&nbsp;reachable items within the price range, return&nbsp;<em><strong>all</strong>&nbsp;of them</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3
<strong>Output:</strong> [[0,1],[1,1],[2,1]]
<strong>Explanation:</strong> You start at (0,0).
With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).
The ranks of these items are:
- (0,1) with distance 1
- (1,1) with distance 2
- (2,1) with distance 3
- (2,2) with distance 4
Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2
<strong>Output:</strong> [[2,1],[1,2]]
<strong>Explanation:</strong> You start at (2,3).
With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).
The ranks of these items are:
- (2,1) with distance 2, price 2
- (1,2) with distance 2, price 3
- (1,1) with distance 3
- (0,1) with distance 4
Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/30/example3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3
<strong>Output:</strong> [[2,1],[2,0]]
<strong>Explanation:</strong> You start at (0,0).
With a price range of [2,3], we can take items from (2,0) and (2,1). 
The ranks of these items are: 
- (2,1) with distance 5
- (2,0) with distance 6
Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). 
Note that k = 3 but there are only 2 reachable items within the price range.
</pre>



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



<ul><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li><li><code>pricing.length == 2</code></li><li><code>2 &lt;= low &lt;= high &lt;= 10<sup>5</sup></code></li><li><code>start.length == 2</code></li><li><code>0 &lt;= row &lt;= m - 1</code></li><li><code>0 &lt;= col &lt;= n - 1</code></li><li><code>grid[row][col] &gt; 0</code></li><li><code>1 &lt;= k &lt;= m * n</code></li></ul>



<h2><strong>Solution: BFS + Sorting</strong></h2>



<p>Use BFS to collect reachable cells and sort afterwards.</p>



<p>Time complexity: O(mn + KlogK) where K = # of reachable cells.</p>



<p>Space complexity: O(mn)</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;vector&lt;int&gt;&gt; highestRankedKItems(vector&lt;vector&lt;int&gt;&gt;&amp; grid, vector&lt;int&gt;&amp; pricing, vector&lt;int&gt;&amp; start, int k) {
    const int m = grid.size();
    const int n = grid[0].size();    
    const vector&lt;int&gt; dirs{1, 0, -1, 0, 1};    
    vector&lt;vector&lt;int&gt;&gt; seen(m, vector&lt;int&gt;(n));
    seen[start[0]][start[1]] = 1;
    vector&lt;vector&lt;int&gt;&gt; cells;
    queue&lt;array&lt;int, 3&gt;&gt; q;
    q.push({start[0], start[1], 0});
    while (!q.empty()) {
      auto [y, x, d] = q.front(); q.pop();
      if (grid[y][x] &gt;= pricing[0] &amp;&amp; grid[y][x] &lt;= pricing[1])
          cells.push_back({d, grid[y][x], y, x});
      for (int i = 0; i &lt; 4; ++i) {
        const int tx = x + dirs[i];
        const int ty = y + dirs[i + 1];
        if (tx &lt; 0 || tx &gt;= n || ty &lt; 0 || ty &gt;= m 
            || !grid[ty][tx] || seen[ty][tx]++) continue;
        q.push({ty, tx, d + 1});
      }
    }
    sort(begin(cells), end(cells), less&lt;vector&lt;int&gt;&gt;());
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (int i = 0; i &lt; min(k, (int)(cells.size())); ++i)
      ans.push_back({cells[i][2], cells[i][3]});
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/">花花酱 LeetCode 2146. K Highest Ranked Items Within a Price Range</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/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/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 1913. Maximum Product Difference Between Two Pairs</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Dec 2021 03:02:32 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9227</guid>

					<description><![CDATA[<p>The&#160;product difference&#160;between two pairs&#160;(a, b)&#160;and&#160;(c, d)&#160;is defined as&#160;(a * b) - (c * d). For example, the product difference between&#160;(5, 6)&#160;and&#160;(2, 7)&#160;is&#160;(5 * 6) -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/">花花酱 LeetCode 1913. Maximum Product Difference Between Two Pairs</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>The&nbsp;<strong>product difference</strong>&nbsp;between two pairs&nbsp;<code>(a, b)</code>&nbsp;and&nbsp;<code>(c, d)</code>&nbsp;is defined as&nbsp;<code>(a * b) - (c * d)</code>.</p>



<ul><li>For example, the product difference between&nbsp;<code>(5, 6)</code>&nbsp;and&nbsp;<code>(2, 7)</code>&nbsp;is&nbsp;<code>(5 * 6) - (2 * 7) = 16</code>.</li></ul>



<p>Given an integer array&nbsp;<code>nums</code>, choose four&nbsp;<strong>distinct</strong>&nbsp;indices&nbsp;<code>w</code>,&nbsp;<code>x</code>,&nbsp;<code>y</code>, and&nbsp;<code>z</code>&nbsp;such that the&nbsp;<strong>product difference</strong>&nbsp;between pairs&nbsp;<code>(nums[w], nums[x])</code>&nbsp;and&nbsp;<code>(nums[y], nums[z])</code>&nbsp;is&nbsp;<strong>maximized</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;such product difference</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,6,2,7,4]
<strong>Output:</strong> 34
<strong>Explanation:</strong> We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,5,9,7,4,8]
<strong>Output:</strong> 64
<strong>Explanation:</strong> We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
</pre>



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



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



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



<p>Since all the numbers are positive, we just need to find the largest two numbers as the first pair and smallest two numbers are the second pair.</p>



<p>Time complexity: O(nlogn) / sorting, O(n) / finding min/max elements.<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxProductDifference(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    sort(begin(nums), end(nums));
    return nums[n - 1] * nums[n - 2] - nums[0] * nums[1];
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def maxProductDifference(self, nums: List[int]) -&gt; int:
    nums.sort()
    return nums[-1] * nums[-2] - nums[0] * nums[1]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/">花花酱 LeetCode 1913. Maximum Product Difference Between Two Pairs</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-1913-maximum-product-difference-between-two-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2099. Find Subsequence of Length K With the Largest Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2099-find-subsequence-of-length-k-with-the-largest-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2099-find-subsequence-of-length-k-with-the-largest-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Dec 2021 18:32:39 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[k-th]]></category>
		<category><![CDATA[n-th element]]></category>
		<category><![CDATA[quickselect]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9130</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;and an integer&#160;k. You want to find a&#160;subsequence&#160;of&#160;nums&#160;of length&#160;k&#160;that has the&#160;largest&#160;sum. Return&#160;any&#160;such subsequence as an integer array of length&#160;k. A&#160;subsequence&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2099-find-subsequence-of-length-k-with-the-largest-sum/">花花酱 LeetCode 2099. Find Subsequence of Length K With the Largest 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 integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. You want to find a&nbsp;<strong>subsequence&nbsp;</strong>of&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>k</code>&nbsp;that has the&nbsp;<strong>largest</strong>&nbsp;sum.</p>



<p>Return<em>&nbsp;</em><em><strong>any</strong>&nbsp;such subsequence as an integer array of length&nbsp;</em><code>k</code>.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,1,3,3], k = 2
<strong>Output:</strong> [3,3]
<strong>Explanation:</strong>
The subsequence has the largest sum of 3 + 3 = 6.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,-2,3,4], k = 3
<strong>Output:</strong> [-1,3,4]
<strong>Explanation:</strong> 
The subsequence has the largest sum of -1 + 3 + 4 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,4,3,3], k = 2
<strong>Output:</strong> [3,4]
<strong>Explanation:</strong>
The subsequence has the largest sum of 3 + 4 = 7. 
Another possible subsequence is [4, 3].
</pre>



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



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



<h2><strong>Solution 1: Full sorting + Hashtable</strong></h2>



<p>Make a copy of the original array, sort it in whole and put k largest elements in a hashtable.</p>



<p>Scan the original array and append the number to the answer array if it&#8217;s in the hashtable.</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; maxSubsequence(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;int&gt; ans;
    vector&lt;int&gt; s(nums);
    sort(rbegin(s), rend(s));
    unordered_map&lt;int, int&gt; m;
    for (int i = 0; i &lt; k; ++i) ++m[s[i]];
    for (int x : nums) 
      if (--m[x] &gt;= 0) 
        ans.push_back(x);
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: k-th element</strong></h2>



<p>Use quick select / partial sort to find the k-th largest element of the array. Any number greater than that must be in the sequence. The tricky part is: what about the pivot itself? We couldn&#8217;t include &#8217;em all blindly. Need to figure out how many copies of the pivot is there in the k largest and only include as many as of that in the final answer.</p>



<p>Time complexity: O(n+k)<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; maxSubsequence(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;int&gt; ans;
    vector&lt;int&gt; s(nums);
    nth_element(begin(s), begin(s) + k - 1, end(s), greater&lt;int&gt;());
    const int pivot = s[k - 1];
    // How many pivots in the largest k elements.
    int left = count(begin(s), begin(s) + k, pivot);    
    for (size_t i = 0; i != nums.size(); ++i)
      if (nums[i] &gt; pivot || (nums[i] == pivot &amp;&amp; --left &gt;= 0)) 
        ans.push_back(nums[i]);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2099-find-subsequence-of-length-k-with-the-largest-sum/">花花酱 LeetCode 2099. Find Subsequence of Length K With the Largest 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/algorithms/array/leetcode-2099-find-subsequence-of-length-k-with-the-largest-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2089. Find Target Indices After Sorting Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2089-find-target-indices-after-sorting-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2089-find-target-indices-after-sorting-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 16:33:35 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8850</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;and a target element&#160;target. A&#160;target index&#160;is an index&#160;i&#160;such that&#160;nums[i] == target. Return&#160;a list of the target indices of&#160;nums&#160;after&#160;sorting&#160;nums&#160;in&#160;non-decreasing&#160;order. If there are&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2089-find-target-indices-after-sorting-array/">花花酱 LeetCode 2089. Find Target Indices After Sorting Array</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>nums</code>&nbsp;and a target element&nbsp;<code>target</code>.</p>



<p>A&nbsp;<strong>target index</strong>&nbsp;is an index&nbsp;<code>i</code>&nbsp;such that&nbsp;<code>nums[i] == target</code>.</p>



<p>Return&nbsp;<em>a list of the target indices of</em>&nbsp;<code>nums</code>&nbsp;after<em>&nbsp;sorting&nbsp;</em><code>nums</code><em>&nbsp;in&nbsp;<strong>non-decreasing</strong>&nbsp;order</em>. If there are no target indices, return&nbsp;<em>an&nbsp;<strong>empty</strong>&nbsp;list</em>. The returned list must be sorted in&nbsp;<strong>increasing</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,5,2,3], target = 2
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> After sorting, nums is [1,<strong>2</strong>,<strong>2</strong>,3,5].
The indices where nums[i] == 2 are 1 and 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,5,2,3], target = 3
<strong>Output:</strong> [3]
<strong>Explanation:</strong> After sorting, nums is [1,2,2,<strong>3</strong>,5].
The index where nums[i] == 3 is 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,5,2,3], target = 5
<strong>Output:</strong> [4]
<strong>Explanation:</strong> After sorting, nums is [1,2,2,3,<strong>5</strong>].
The index where nums[i] == 5 is 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,5,2,3], target = 4
<strong>Output:</strong> []
<strong>Explanation:</strong> There are no elements in nums with value 4.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 100</code></li><li><code>1 &lt;= nums[i], target &lt;= 100</code></li></ul>



<h2><strong>Solution: Sorting</strong></h2>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</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; targetIndices(vector&lt;int&gt;&amp; nums, int target) {
    sort(begin(nums), end(nums));
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; nums.size(); ++i)
      if (nums[i] == target) ans.push_back(i);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2089-find-target-indices-after-sorting-array/">花花酱 LeetCode 2089. Find Target Indices After Sorting Array</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/array/leetcode-2089-find-target-indices-after-sorting-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Jan 2021 21:10:47 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7990</guid>

					<description><![CDATA[<p>You are given a binary matrix&#160;matrix&#160;of size&#160;m x n, and you are allowed to rearrange the&#160;columns&#160;of the&#160;matrix&#160;in any order. Return&#160;the area of the largest submatrix&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/">花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</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-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1727. Largest Submatrix With Rearrangements - 刷题找工作 EP380" width="500" height="281" src="https://www.youtube.com/embed/eX0lXwGu3OE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a binary matrix&nbsp;<code>matrix</code>&nbsp;of size&nbsp;<code>m x n</code>, and you are allowed to rearrange the&nbsp;<strong>columns</strong>&nbsp;of the&nbsp;<code>matrix</code>&nbsp;in any order.</p>



<p>Return&nbsp;<em>the area of the largest submatrix within&nbsp;</em><code>matrix</code><em>&nbsp;where&nbsp;<strong>every</strong>&nbsp;element of the submatrix is&nbsp;</em><code>1</code><em>&nbsp;after reordering the columns optimally.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[0,0,1],[1,1,1],[1,0,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,0,1,0,1]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,1,0],[1,0,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[0,0],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> As there are no 1s, no submatrix of 1s can be formed and the area is 0.</pre>



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



<ul><li><code>m == matrix.length</code></li><li><code>n == matrix[i].length</code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>matrix[i][j]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: DP + Sorting</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png" alt="" class="wp-image-7997" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-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/01/1727-ep380-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2.png" alt="" class="wp-image-7999" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Preprocess each column, for col j, matrix[i][j] := length consecutive ones of col j.</p>



<pre class="wp-block-code;crayon:false"><code>&#091;0,0,1]    &#091;0,0,1]
&#091;1,1,1] =&gt; &#091;1,1,2]
&#091;1,0,1]    &#091;2,0,3]</code></pre>



<p>Then we enumerate ending row, for each ending row i, we sort row[i] in deceasing order</p>



<p>e.g. i = 2</p>



<pre class="wp-block-code;crayon:false"><code>&#091;0,0,1]                  &#091;-,-,-]
&#091;1,1,2] sort by row 2 =&gt; &#091;-,-,-]
&#091;2,0,3]                  &#091;3,2,0]</code></pre>



<p>row[2][1] = 3, means there is a 3&#215;1 all ones sub matrix, area = 3<br>row[2][2] = 2, means there is a 2&#215;2 all ones sub matrix, area = 4.</p>



<p>Time complexity: O(m*n*log(n))<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int largestSubmatrix(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    for (int j = 0; j &lt; n; ++j)
      for (int i = 1; i &lt; m; ++i)      
        if (matrix[i][j]) matrix[i][j] += matrix[i - 1][j];          
    
    int ans = 0;
    for (int i = 0; i &lt; m; ++i) {
      sort(rbegin(matrix[i]), rend(matrix[i]));
      for (int j = 0; j &lt; n; ++j)
        ans = max(ans, (j + 1) * matrix[i][j]);        
    }
    return ans;    
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/">花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1707. Maximum XOR With an Element From Array</title>
		<link>https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/</link>
					<comments>https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 21:54:20 +0000</pubDate>
				<category><![CDATA[Trie]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[trie]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7871</guid>

					<description><![CDATA[<p>You are given an array&#160;nums&#160;consisting of non-negative integers. You are also given a&#160;queries&#160;array, where&#160;queries[i] = [xi, mi]. The answer to the&#160;ith&#160;query is the maximum bitwise&#160;XOR&#160;value&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/">花花酱 LeetCode 1707. Maximum XOR With an Element From Array</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 1707. Maximum XOR With an Element From Array - 刷题找工作 EP377" width="500" height="281" src="https://www.youtube.com/embed/k0e9tM7gU3E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>nums</code>&nbsp;consisting of non-negative integers. You are also given a&nbsp;<code>queries</code>&nbsp;array, where&nbsp;<code>queries[i] = [x<sub>i</sub>, m<sub>i</sub>]</code>.</p>



<p>The answer to the&nbsp;<code>i<sup>th</sup></code>&nbsp;query is the maximum bitwise&nbsp;<code>XOR</code>&nbsp;value of&nbsp;<code>x<sub>i</sub></code>&nbsp;and any element of&nbsp;<code>nums</code>&nbsp;that does not exceed&nbsp;<code>m<sub>i</sub></code>. In other words, the answer is&nbsp;<code>max(nums[j] XOR x<sub>i</sub>)</code>&nbsp;for all&nbsp;<code>j</code>&nbsp;such that&nbsp;<code>nums[j] &lt;= m<sub>i</sub></code>. If all elements in&nbsp;<code>nums</code>&nbsp;are larger than&nbsp;<code>m<sub>i</sub></code>, then the answer is&nbsp;<code>-1</code>.</p>



<p>Return&nbsp;<em>an integer array&nbsp;</em><code>answer</code><em>&nbsp;where&nbsp;</em><code>answer.length == queries.length</code><em>&nbsp;and&nbsp;</em><code>answer[i]</code><em>&nbsp;is the answer to the&nbsp;</em><code>i<sup>th</sup></code><em>&nbsp;query.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
<strong>Output:</strong> [3,3,7]
<strong>Explanation:</strong>
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
</pre>



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



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



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



<ul><li><code>1 &lt;= nums.length, queries.length &lt;= 10<sup>5</sup></code></li><li><code>queries[i].length == 2</code></li><li><code>0 &lt;= nums[j], x<sub>i</sub>, m<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Trie on the fly</strong></h2>



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



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



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



<p>Similar idea to <a href="https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/">https://zxi.mytechroad.com/blog/trie/leetcode-421-maximum-xor-of-two-numbers-in-an-array/</a></p>



<p>We can build the trie on the fly by sorting nums in ascending order and queries by its limit, insert nums into the trie up the limit.</p>



<p>Time complexity: O(nlogn + QlogQ)<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 Trie {
public:
  Trie(): children{nullptr, nullptr} {}  
  Trie* children[2];
};
class Solution {
public:
  vector&lt;int&gt; maximizeXor(vector&lt;int&gt;&amp; nums, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    const int n = nums.size();
    sort(begin(nums), end(nums));    
    
    const int Q = queries.size();
    for (int i = 0; i &lt; Q; ++i)
      queries[i].push_back(i);
    sort(begin(queries), end(queries), [](const auto&amp; q1, const auto&amp; q2) {
      return q1[1] &lt; q2[1];
    });
    
    Trie root;    
    auto insert = [&amp;](int num) {
      Trie* node = &amp;root; 
      for (int i = 31; i &gt;= 0; --i) {
        int bit = (num &gt;&gt; i) &amp; 1;
        if (!node-&gt;children[bit])
          node-&gt;children[bit] = new Trie();
        node = node-&gt;children[bit];
      }
    };
        
    auto query = [&amp;](int num) {
      Trie* node = &amp;root;
      int sum = 0;
      for (int i = 31; i &gt;= 0; --i) {
        if (!node) return -1;
        int bit = (num &gt;&gt; i) &amp; 1;
        if (node-&gt;children[1 - bit]) {
          sum |= (1 &lt;&lt; i);
          node = node-&gt;children[1 - bit];
        } else {
          node = node-&gt;children[bit];
        }
      }
      return sum;
    };
    
    vector&lt;int&gt; ans(Q);
    int i = 0;
    for (const auto&amp; q : queries) {
      while (i &lt; n &amp;&amp; nums[i] &lt;= q[1]) insert(nums[i++]);
      ans[q[2]] = query(q[0]);
    }  
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/trie/leetcode-1707-maximum-xor-with-an-element-from-array/">花花酱 LeetCode 1707. Maximum XOR With an Element From Array</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/trie/leetcode-1707-maximum-xor-with-an-element-from-array/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 1697. Checking Existence of Edge Length Limited Paths</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1697-checking-existence-of-edge-length-limited-paths/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1697-checking-existence-of-edge-length-limited-paths/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 20 Dec 2020 10:00:20 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7830</guid>

					<description><![CDATA[<p>An undirected graph of&#160;n&#160;nodes is defined by&#160;edgeList, where&#160;edgeList[i] = [ui, vi, disi]&#160;denotes an edge between nodes&#160;ui&#160;and&#160;vi&#160;with distance&#160;disi. Note that there may be&#160;multiple&#160;edges between two nodes.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1697-checking-existence-of-edge-length-limited-paths/">花花酱 LeetCode 1697. Checking Existence of Edge Length Limited Paths</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>An undirected graph of&nbsp;<code>n</code>&nbsp;nodes is defined by&nbsp;<code>edgeList</code>, where&nbsp;<code>edgeList[i] = [u<sub>i</sub>, v<sub>i</sub>, dis<sub>i</sub>]</code>&nbsp;denotes an edge between nodes&nbsp;<code>u<sub>i</sub></code>&nbsp;and&nbsp;<code>v<sub>i</sub></code>&nbsp;with distance&nbsp;<code>dis<sub>i</sub></code>. Note that there may be&nbsp;<strong>multiple</strong>&nbsp;edges between two nodes.</p>



<p>Given an array&nbsp;<code>queries</code>, where&nbsp;<code>queries[j] = [p<sub>j</sub>, q<sub>j</sub>, limit<sub>j</sub>]</code>, your task is to determine for each&nbsp;<code>queries[j]</code>&nbsp;whether there is a path between&nbsp;<code>p<sub>j</sub></code>&nbsp;and&nbsp;<code>q<sub>j</sub></code>such that each edge on the path has a distance&nbsp;<strong>strictly less than</strong>&nbsp;<code>limit<sub>j</sub></code>&nbsp;.</p>



<p>Return&nbsp;<em>a&nbsp;<strong>boolean array</strong>&nbsp;</em><code>answer</code><em>, where&nbsp;</em><code>answer.length == queries.length</code>&nbsp;<em>and the&nbsp;</em><code>j<sup>th</sup></code>&nbsp;<em>value of&nbsp;</em><code>answer</code>&nbsp;<em>is&nbsp;</em><code>true</code><em>&nbsp;if there is a path for&nbsp;</em><code>queries[j]</code><em>&nbsp;is&nbsp;</em><code>true</code><em>, and&nbsp;</em><code>false</code><em>&nbsp;otherwise</em>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]
<strong>Output:</strong> [false,true]
<strong>Explanation:</strong> The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -&gt; 1 -&gt; 2) of two edges with distances less than 5, thus we return true for this query.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]
<strong>Output:</strong> [true,false]
<strong>Exaplanation:</strong> The above figure shows the given graph.
</pre>



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



<ul><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= edgeList.length, queries.length &lt;= 10<sup>5</sup></code></li><li><code>edgeList[i].length == 3</code></li><li><code>queries[j].length == 3</code></li><li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub>, p<sub>j</sub>, q<sub>j</sub>&nbsp;&lt;= n - 1</code></li><li><code>u<sub>i</sub>&nbsp;!= v<sub>i</sub></code></li><li><code>p<sub>j</sub>&nbsp;!= q<sub>j</sub></code></li><li><code>1 &lt;= dis<sub>i</sub>, limit<sub>j</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li>There may be&nbsp;<strong>multiple</strong>&nbsp;edges between two nodes.</li></ul>



<h2><strong>Solution: Union Find</strong></h2>



<p>Since queries are offline, we can reorder them to optimize time complexity. Answer queries by their limits in ascending order while union edges by weights up to the limit. In this case, we just need to go through the entire edge list at most once.</p>



<p>Time complexity: O(QlogQ + ElogE)<br>Space complexity: O(Q + E)</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;bool&gt; distanceLimitedPathsExist(int n, vector&lt;vector&lt;int&gt;&gt;&amp; E, vector&lt;vector&lt;int&gt;&gt;&amp; Q) {
    vector&lt;int&gt; parents(n);
    iota(begin(parents), end(parents), 0);
    function&lt;int(int)&gt; find = [&amp;](int x) {
      return parents[x] == x ? x : parents[x] = find(parents[x]);
    };
    const int m = Q.size();
    for (int i = 0; i &lt; m; ++i) Q[i].push_back(i);
    // Sort edges by weight in ascending order.
    sort(begin(E), end(E), [](const auto&amp; a, const auto&amp; b) { return a[2] &lt; b[2]; });
    // Sort queries by limit in ascending order
    sort(begin(Q), end(Q), [](const auto&amp; a, const auto&amp; b) { return a[2] &lt; b[2]; });
    vector&lt;bool&gt; ans(m);
    int i = 0;
    for (const auto&amp; q : Q) {      
      while (i &lt; E.size() &amp;&amp; E[i][2] &lt; q[2])
        parents[find(E[i++][0])] = find(E[i][1]);        
      ans[q[3]] = find(q[0]) == find(q[1]);
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1697-checking-existence-of-edge-length-limited-paths/">花花酱 LeetCode 1697. Checking Existence of Edge Length Limited Paths</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/graph/leetcode-1697-checking-existence-of-edge-length-limited-paths/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1691. Maximum Height by Stacking Cuboids</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1691-maximum-height-by-stacking-cuboids/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1691-maximum-height-by-stacking-cuboids/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 14 Dec 2020 07:31:58 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7814</guid>

					<description><![CDATA[<p>Given&#160;n&#160;cuboids&#160;where the dimensions of the&#160;ith&#160;cuboid is&#160;cuboids[i] = [widthi, lengthi, heighti]&#160;(0-indexed). Choose a&#160;subset&#160;of&#160;cuboids&#160;and place them on each other. You can place cuboid&#160;i&#160;on cuboid&#160;j&#160;if&#160;widthi&#160;&#60;= widthj&#160;and&#160;lengthi&#160;&#60;= lengthj&#160;and&#160;heighti&#160;&#60;= heightj.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1691-maximum-height-by-stacking-cuboids/">花花酱 LeetCode 1691. Maximum Height by Stacking Cuboids</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>Given&nbsp;<code>n</code>&nbsp;<code>cuboids</code>&nbsp;where the dimensions of the&nbsp;<code>i<sup>th</sup></code>&nbsp;cuboid is&nbsp;<code>cuboids[i] = [width<sub>i</sub>, length<sub>i</sub>, height<sub>i</sub>]</code>&nbsp;(<strong>0-indexed</strong>). Choose a&nbsp;<strong>subset</strong>&nbsp;of&nbsp;<code>cuboids</code>&nbsp;and place them on each other.</p>



<p>You can place cuboid&nbsp;<code>i</code>&nbsp;on cuboid&nbsp;<code>j</code>&nbsp;if&nbsp;<code>width<sub>i</sub>&nbsp;&lt;= width<sub>j</sub></code>&nbsp;and&nbsp;<code>length<sub>i</sub>&nbsp;&lt;= length<sub>j</sub></code>&nbsp;and&nbsp;<code>height<sub>i</sub>&nbsp;&lt;= height<sub>j</sub></code>. You can rearrange any cuboid&#8217;s dimensions by rotating it to put it on another cuboid.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum height</strong>&nbsp;of the stacked</em>&nbsp;<code>cuboids</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/10/21/image.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cuboids = [[50,45,20],[95,37,53],[45,23,12]]
<strong>Output:</strong> 190
<strong>Explanation:</strong>
Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.
Cuboid 0 is placed next with the 45x20 side facing down with height 50.
Cuboid 2 is placed next with the 23x12 side facing down with height 45.
The total height is 95 + 50 + 45 = 190.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cuboids = [[38,25,45],[76,35,3]]
<strong>Output:</strong> 76
<strong>Explanation:</strong>
You can't place any of the cuboids on the other.
We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
<strong>Output:</strong> 102
<strong>Explanation:</strong>
After rearranging the cuboids, you can see that all cuboids have the same dimension.
You can place the 11x7 side down on all cuboids so their heights are 17.
The maximum height of stacked cuboids is 6 * 17 = 102.
</pre>



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



<ul><li><code>n == cuboids.length</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li><code>1 &lt;= width<sub>i</sub>, length<sub>i</sub>, height<sub>i</sub>&nbsp;&lt;= 100</code></li></ul>



<h2><strong>Solution: Math/Greedy + DP</strong></h2>



<p>Direct DP is very hard, since there is no orders.</p>



<p>We have to find some way to sort the cuboids such that cuboid i can NOT stack on cuboid j if i &gt; j. Then dp[i] = max(dp[j]) + height[i], 0 &lt;= j &lt; i, for each i, find the best base j and stack on top of it.<br>ans = max(dp)</p>



<p>We can sort the cuboids by their sorted dimensions, and cuboid i can stack stack onto cuboid j if and only if w[i] &lt;= w[j] and l[i] &lt;= l[j] and h[i] &lt;= h[j].</p>



<p>First of all, we need to prove that all heights must come from the largest dimension of each cuboid. <br><br>1. If the top of the stack is A1*A2*A3, A3 &lt; max(A1, A2), we can easily swap A3 with max(A1, A2), it&#8217;s still stackable but we get larger heights.<br>e.g. 3x5x4, base is 3&#215;5, height is 4, we can rotate to get base of 3&#215;4 with height of 5.</p>



<p>2. If a middle cuboid A of size A1*A2*A3, assuming A1 &gt;= A2, A1 &gt; A3, on top of A we have another cuboid B of size B1*B2*B3, B1 &lt;= B2 &lt;= B3.<br>We have A1 &gt;= B1, A2 &gt;= B2, A3 &gt;= B3, by rotating A we have A3*A2*A1<br>A3 &gt;= B3 &gt;= B1, A2 &gt;= B2, A1 &gt; A3 &gt;= B3, so B can be still on top of A, and we get larger height.</p>



<p>e.g. A: 3x5x4, B: 2x3x4<br>A -&gt; 3x4x5, B is still stackable.</p>



<p>&#8230;</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxHeight(vector&lt;vector&lt;int&gt;&gt;&amp; A) {
    A.push_back({0, 0, 0});
    const int n = A.size();
    for (auto&amp; box : A) sort(begin(box), end(box));
    sort(begin(A), end(A));
    vector&lt;int&gt; dp(n);
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; i; ++j)
        if (A[i][0] &gt;= A[j][0] &amp;&amp; A[i][1] &gt;= A[j][1] &amp;&amp; A[i][2] &gt;= A[j][2])
          dp[i] = max(dp[i], dp[j] + A[i][2]);
    return *max_element(begin(dp), end(dp));
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1691-maximum-height-by-stacking-cuboids/">花花酱 LeetCode 1691. Maximum Height by Stacking Cuboids</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1691-maximum-height-by-stacking-cuboids/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 1630. Arithmetic Subarrays</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1630-arithmetic-subarrays/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1630-arithmetic-subarrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Oct 2020 05:31:32 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Arithmetic]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(mnlogn)]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7552</guid>

					<description><![CDATA[<p>A sequence of numbers is called&#160;arithmetic&#160;if it consists of at least two elements, and the difference between every two consecutive elements is the same. More&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1630-arithmetic-subarrays/">花花酱 LeetCode 1630. Arithmetic Subarrays</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>A sequence of numbers is called&nbsp;<strong>arithmetic</strong>&nbsp;if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence&nbsp;<code>s</code>&nbsp;is arithmetic if and only if&nbsp;<code>s[i+1] - s[i] == s[1] - s[0]&nbsp;</code>for all valid&nbsp;<code>i</code>.</p>



<p>For example, these are&nbsp;<strong>arithmetic</strong>&nbsp;sequences:</p>



<pre class="crayon-plain-tag">1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9</pre>



<p>The following sequence is not&nbsp;<strong>arithmetic</strong>:</p>



<pre class="wp-block-preformatted;crayon:false">1, 1, 2, 5, 7</pre>



<p>You are given an array of&nbsp;<code>n</code>&nbsp;integers,&nbsp;<code>nums</code>, and two arrays of&nbsp;<code>m</code>&nbsp;integers each,&nbsp;<code>l</code>&nbsp;and&nbsp;<code>r</code>, representing the&nbsp;<code>m</code>&nbsp;range queries, where the&nbsp;<code>i<sup>th</sup></code>&nbsp;query is the range&nbsp;<code>[l[i], r[i]]</code>. All the arrays are&nbsp;<strong>0-indexed</strong>.</p>



<p>Return&nbsp;<em>a list of&nbsp;</em><code>boolean</code>&nbsp;<em>elements</em>&nbsp;<code>answer</code><em>, where</em>&nbsp;<code>answer[i]</code>&nbsp;<em>is</em>&nbsp;<code>true</code>&nbsp;<em>if the subarray</em>&nbsp;<code>nums[l[i]], nums[l[i]+1], ... , nums[r[i]]</code><em>&nbsp;can be&nbsp;<strong>rearranged</strong>&nbsp;to form an&nbsp;<strong>arithmetic</strong>&nbsp;sequence, and</em>&nbsp;<code>false</code>&nbsp;<em>otherwise.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = <code>[4,6,5,9,3,7]</code>, l = <code>[0,0,2]</code>, r = <code>[2,3,5]</code>
<strong>Output:</strong> <code>[true,false,true]</code>
<strong>Explanation:</strong>
In the 0<sup>th</sup> query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.
In the 1<sup>st</sup> query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.
In the 2<sup>nd</sup> query, the subarray is <code>[5,9,3,7]. This</code> can be rearranged as <code>[3,5,7,9]</code>, which is an arithmetic sequence.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
<strong>Output:</strong> [false,true,false,false,true,true]
</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>m == l.length</code></li><li><code>m == r.length</code></li><li><code>2 &lt;= n &lt;= 500</code></li><li><code>1 &lt;= m &lt;= 500</code></li><li><code>0 &lt;= l[i] &lt; r[i] &lt; n</code></li><li><code>-10<sup>5</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



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



<p>Sort the range of each query and check.</p>



<p>Time complexity: O(nlogn * m)<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;bool&gt; checkArithmeticSubarrays(vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; l, vector&lt;int&gt;&amp; r) {
    vector&lt;bool&gt; ans(l.size(), true);
    for (int i = 0; i &lt; l.size(); ++i) {
      vector&lt;int&gt; arr(begin(nums) + l[i], begin(nums) + r[i] + 1);
      sort(begin(arr), end(arr));
      const int d = arr[1] - arr[0];
      for (int j = 2; j &lt; arr.size() &amp;&amp; ans[i]; ++j)
        ans[i] = ans[i] &amp;&amp; (arr[j] - arr[j - 1] == d);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1630-arithmetic-subarrays/">花花酱 LeetCode 1630. Arithmetic Subarrays</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/array/leetcode-1630-arithmetic-subarrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
