<?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>O(nlogn) Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/onlogn/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/onlogn/</link>
	<description></description>
	<lastBuildDate>Mon, 21 Mar 2022 12:41:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>O(nlogn) Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/onlogn/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2208. Minimum Operations to Halve Array Sum</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Mar 2022 12:21:32 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[priority_queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9580</guid>

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



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



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



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



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



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



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



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



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



<p>Always half the largest number, put all the numbers onto a max heap (priority queue), extract the largest one, and put reduced number back.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int halveArray(vector&lt;int&gt;&amp; nums) {
    double sum = accumulate(begin(nums), end(nums), 0.0);
    priority_queue&lt;double&gt; q;
    for (int num : nums) q.push(num);
    int ans = 0;
    for (double cur = sum; cur &gt; sum / 2; ++ans) {    
      double num = q.top(); q.pop();
      cur -= num / 2;
      q.push(num / 2);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/">花花酱 LeetCode 2208. Minimum Operations to Halve Array Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 912. Sort an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Feb 2020 17:49:53 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[heapsort]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6226</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/">花花酱 LeetCode 912. Sort an 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>Given an array of integers&nbsp;<code>nums</code>, sort the array in ascending order.</p>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,1,1,2,0,0]
<strong>Output:</strong> [0,0,1,1,2,5]
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 50000</code></li><li><code>-50000 &lt;= nums[i] &lt;= 50000</code></li></ul>



<p>Since n &lt;= 50000, any O(n^2) won&#8217;t pass, we need O(nlogn) or better</p>



<h2><strong>Solution 1: QuickSort</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, 60 ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    function&lt;void(int, int)&gt; quickSort = [&amp;](int l, int r) {
      if (l &gt;= r) return;      
      int i = l;
      int j = r;
      int p = nums[l + rand() % (r - l + 1)];
      while (i &lt;= j) {
        while (nums[i] &lt; p) ++i;
        while (nums[j] &gt; p) --j;
        if (i &lt;= j)
          swap(nums[i++], nums[j--]);
      }
      quickSort(l, j);
      quickSort(i, r);
    };
    quickSort(0, nums.size() - 1);
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Counting Sort</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(max(nums) &#8211; min(nums))</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 54 ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    auto [min_it, max_it] = minmax_element(begin(nums), end(nums));
    int l = *min_it, r = *max_it;
    vector&lt;int&gt; count(r - l + 1);
    for (int n : nums) ++count[n - l];
    int index = 0;
    for (int i = 0; i &lt; count.size(); ++i)
      while (count[i]--) nums[index++] = i + l;
    return nums;
  }
};</pre>
</div></div>



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



<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, 72ms
class Solution {
public:
  vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
    priority_queue&lt;int&gt; q(begin(nums), end(nums));
    int i = nums.size();
    while (!q.empty()) {
      nums[--i] = q.top();
      q.pop();
    }
    return nums;
  }
};</pre>
</div></div>



<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; sortArray(vector&lt;int&gt;&amp; nums) {
    auto heapify = [&amp;](int i, int e) {
      while (i &lt;= e) {
        int l = 2 * i + 1;
        int r = 2 * i + 2;
        int j = i;
        if (l &lt;= e &amp;&amp; nums[l] &gt; nums[j]) j = l;
        if (r &lt;= e &amp;&amp; nums[r] &gt; nums[j]) j = r;
        if (j == i) break;
        swap(nums[i], nums[j]);
        swap(i, j);
      }
    };
    
    const int n = nums.size();
    
    // Init heap
    for (int i = n / 2; i &gt;= 0; i--)
      heapify(i, n - 1);
    
    // Get min.
    for (int i = n - 1; i &gt;= 1; i--) {
      swap(nums[0], nums[i]);
      heapify(0, i - 1);    
    }
    
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 3: MergeSort</strong></h2>



<p>Time complexity: O(nlogn)<br>Space complexity: O(logn + 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; sortArray(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; t(nums.size());
    function&lt;void(int, int)&gt; mergeSort = [&amp;](int l, int r) {
      if (l + 1 &gt;= r) return;
      int m = l + (r - l) / 2;
      mergeSort(l, m);
      mergeSort(m, r);
      int i1 = l;
      int i2 = m;
      int index = 0;
      while (i1 &lt; m || i2 &lt; r)
        if (i2 == r || (i1 &lt; m &amp;&amp; nums[i1] &lt; nums[i2]))
          t[index++] = nums[i1++];
        else
          t[index++] = nums[i2++];      
      std::copy(begin(t), begin(t) + index, begin(nums) + l);
    };
    
    mergeSort(0, nums.size());
    return nums;
  }
};</pre>
</div></div>



<h2><strong>Solution 4: BST</strong></h2>



<p>Time complexity: (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; sortArray(vector&lt;int&gt;&amp; nums) {
    multiset&lt;int&gt; s(begin(nums), end(nums));
    return {begin(s), end(s)};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-912-sort-an-array/">花花酱 LeetCode 912. Sort an 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-912-sort-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1333-filter-restaurants-by-vegan-friendly-price-and-distance/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1333-filter-restaurants-by-vegan-friendly-price-and-distance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 27 Jan 2020 05:02:04 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6146</guid>

					<description><![CDATA[<p>Given the array&#160;restaurants&#160;where &#160;restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters. The&#160;veganFriendly&#160;filter will be either&#160;true&#160;(meaning you should&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1333-filter-restaurants-by-vegan-friendly-price-and-distance/">花花酱 LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance</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 the array&nbsp;<code>restaurants</code>&nbsp;where &nbsp;<code>restaurants[i] = [id<sub>i</sub>, rating<sub>i</sub>, veganFriendly<sub>i</sub>, price<sub>i</sub>, distance<sub>i</sub>]</code>. You have to filter the restaurants using three filters.</p>



<p>The&nbsp;<code>veganFriendly</code>&nbsp;filter will be either&nbsp;<em>true</em>&nbsp;(meaning you should only include restaurants with&nbsp;<code>veganFriendly<sub>i</sub></code>&nbsp;set to true)&nbsp;or&nbsp;<em>false</em>&nbsp;(meaning you can include any restaurant). In addition, you have the filters&nbsp;<code>maxPrice</code>&nbsp;and&nbsp;<code>maxDistance</code>&nbsp;which&nbsp;are the maximum value for price and distance of restaurants you should consider respectively.</p>



<p>Return the array of restaurant&nbsp;<em><strong>IDs</strong></em>&nbsp;after filtering, ordered by&nbsp;<strong>rating</strong>&nbsp;from highest to lowest. For restaurants with the same rating, order them by&nbsp;<em><strong>id</strong></em>&nbsp;from highest to lowest. For simplicity&nbsp;<code>veganFriendly<sub>i</sub></code>&nbsp;and&nbsp;<code>veganFriendly</code>&nbsp;take value&nbsp;<em>1</em>&nbsp;when it is&nbsp;<em>true</em>, and&nbsp;<em>0</em>&nbsp;when it is&nbsp;<em>false</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
<strong>Output:</strong> [3,1,5] 
<strong>Explanation: 
</strong>The restaurants are:
Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] 
After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
<strong>Output:</strong> [4,3,2,1,5]
<strong>Explanation:</strong> The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
<strong>Output:</strong> [4,5]
</pre>



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



<ul><li><code>1 &lt;=&nbsp;restaurants.length &lt;= 10^4</code></li><li><code>restaurants[i].length == 5</code></li><li><code>1 &lt;=&nbsp;id<sub>i</sub>, rating<sub>i</sub>, price<sub>i</sub>, distance<sub>i&nbsp;</sub>&lt;= 10^5</code></li><li><code>1 &lt;=&nbsp;maxPrice,&nbsp;maxDistance &lt;= 10^5</code></li><li><code>veganFriendly<sub>i</sub></code>&nbsp;and&nbsp;<code>veganFriendly</code>&nbsp;are&nbsp;0 or 1.</li><li>All&nbsp;<code>id<sub>i</sub></code>&nbsp;are distinct.</li></ul>



<h2><strong>Solution</strong></h2>



<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; filterRestaurants(vector&lt;vector&lt;int&gt;&gt;&amp; restaurants, int veganFriendly, int maxPrice, int maxDistance) {
    vector&lt;pair&lt;int, int&gt;&gt; rs; // &lt;rating, id&gt;
    for (auto&amp; r : restaurants)
      if ((!veganFriendly || veganFriendly &amp;&amp; r[2]) &amp;&amp; r[3] &lt;= maxPrice &amp;&amp; r[4] &lt;= maxDistance)
        rs.emplace_back(r[1], r[0]);
    
    sort(rbegin(rs), rend(rs));    
    vector&lt;int&gt; ans;
    for (const auto&amp; r : rs) ans.push_back(r.second);
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1333-filter-restaurants-by-vegan-friendly-price-and-distance/">花花酱 LeetCode 1333. Filter Restaurants by Vegan-Friendly, Price and Distance</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1333-filter-restaurants-by-vegan-friendly-price-and-distance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1326. Minimum Number of Taps to Open to Water a Garden</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1326-minimum-number-of-taps-to-open-to-water-a-garden/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1326-minimum-number-of-taps-to-open-to-water-a-garden/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Jan 2020 00:48:50 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6112</guid>

					<description><![CDATA[<p>There is a one-dimensional garden on the x-axis. The garden starts at the point&#160;0&#160;and ends at the point&#160;n. (i.e The length of the garden is&#160;n).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1326-minimum-number-of-taps-to-open-to-water-a-garden/">花花酱 LeetCode 1326. Minimum Number of Taps to Open to Water a Garden</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1326. Minimum Number of Taps to Open to Water a Garden - 刷题找工作 EP301" width="500" height="375" src="https://www.youtube.com/embed/G88X89Eo2C0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There is a one-dimensional garden on the x-axis. The garden starts at the point&nbsp;<code>0</code>&nbsp;and ends at the point&nbsp;<code>n</code>. (i.e The length of the garden is&nbsp;<code>n</code>).</p>



<p>There are&nbsp;<code>n + 1</code>&nbsp;taps located&nbsp;at points&nbsp;<code>[0, 1, ..., n]</code>&nbsp;in the garden.</p>



<p>Given an integer&nbsp;<code>n</code>&nbsp;and an integer array&nbsp;<code>ranges</code>&nbsp;of length&nbsp;<code>n + 1</code>&nbsp;where&nbsp;<code>ranges[i]</code>&nbsp;(0-indexed) means the&nbsp;<code>i-th</code>&nbsp;tap can water the area&nbsp;<code>[i - ranges[i], i + ranges[i]]</code>&nbsp;if it was open.</p>



<p>Return&nbsp;<em>the minimum number of taps</em>&nbsp;that should be open to water the whole garden, If the garden cannot be watered return&nbsp;<strong>-1</strong>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/16/1685_example_1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, ranges = [3,4,1,1,0,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, ranges = [0,0,0,0]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Even if you activate all the four taps you cannot water the whole garden.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, ranges = [1,2,1,0,2,1,0,1]
<strong>Output:</strong> 3
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 8, ranges = [4,0,0,0,0,0,0,0,4]
<strong>Output:</strong> 2
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 8, ranges = [4,0,0,0,4,0,0,0,4]
<strong>Output:</strong> 1
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10^4</code></li><li><code>ranges.length == n + 1</code></li><li><code>0 &lt;= ranges[i] &lt;= 100</code></li></ul>



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



<p>Reduce to <a href="https://zxi.mytechroad.com/blog/leetcode/leetcode-weekly-contest-131-1021-1022-1023-1024/">1024. Video Stitching</a></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 minTaps(int n, vector&lt;int&gt;&amp; ranges) {
    vector&lt;pair&lt;int, int&gt;&gt; t;
    // O(n) reduction
    for (int i = 0; i &lt;= n; ++i)
      t.emplace_back(max(0, i - ranges[i]), 
                     min(i + ranges[i], n));
    
    // 1024. Video Stiching
    sort(begin(t), end(t));
    int ans = 0;
    int i = 0;
    int l = 0;
    int e = 0;
    while (e &lt; n) {
      // Extend to the right most w.r.t t[i].first &lt;= l
      while (i &lt;= n &amp;&amp; t[i].first &lt;= l)
        e = max(e, t[i++].second);
      if (l == e) return -1; // Can not extend
      l = e;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>



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



<p>Reduce to <a href="https://zxi.mytechroad.com/blog/greedy/leetcode-45-jump-game-ii/">45. Jump Game II</a></p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minTaps(int n, vector&lt;int&gt;&amp; ranges) {
    vector&lt;int&gt; nums(ranges.size());
    for (int i = 0; i &lt;= n; ++i) {
      int s = max(0, i - ranges[i]);      
      nums[s] = max(nums[s], i + ranges[i]);
    }    
    // 45. Jump Game II
    int steps = 0;
    int l = 0;
    int e = 0;
    for (int i = 0; i &lt;= n; ++i) {
      if (i &gt; e) return -1;
      if (i &gt; l) { ++steps; l = e; }
      e = max(e, nums[i]);
    }
    return steps;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1326-minimum-number-of-taps-to-open-to-water-a-garden/">花花酱 LeetCode 1326. Minimum Number of Taps to Open to Water a Garden</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-1326-minimum-number-of-taps-to-open-to-water-a-garden/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1317. Convert Integer to the Sum of Two No-Zero Integers</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1317-convert-integer-to-the-sum-of-two-no-zero-integers/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1317-convert-integer-to-the-sum-of-two-no-zero-integers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 14 Jan 2020 05:29:34 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[digits]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6090</guid>

					<description><![CDATA[<p>Given an integer&#160;n. No-Zero integer is a positive integer which&#160;doesn&#8217;t contain any 0&#160;in its decimal representation. Return&#160;a list of two integers&#160;[A, B]&#160;where: A&#160;and&#160;B&#160;are No-Zero integers.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1317-convert-integer-to-the-sum-of-two-no-zero-integers/">花花酱 LeetCode 1317. Convert Integer to the Sum of Two No-Zero Integers</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 an integer&nbsp;<code>n</code>. No-Zero integer is a positive integer which&nbsp;<strong>doesn&#8217;t contain any 0</strong>&nbsp;in its decimal representation.</p>



<p>Return&nbsp;<em>a list of two integers</em>&nbsp;<code>[A, B]</code>&nbsp;where:</p>



<ul><li><code>A</code>&nbsp;and&nbsp;<code>B</code>&nbsp;are No-Zero integers.</li><li><code>A + B = n</code></li></ul>



<p>It&#8217;s guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them.</p>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 2
&lt;strong&gt;Output:&lt;/strong&gt; [1,1]
&lt;strong&gt;Explanation:&lt;/strong&gt; A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 11
&lt;strong&gt;Output:&lt;/strong&gt; [2,9]</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 10000
&lt;strong&gt;Output:&lt;/strong&gt; [1,9999]</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 69
&lt;strong&gt;Output:&lt;/strong&gt; [1,68]</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 1010
&lt;strong&gt;Output:&lt;/strong&gt; [11,999]</pre>



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



<ul><li><code>2 &lt;= n &lt;= 10^4</code></li></ul>



<h2><strong>Solution: Brute Force</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; getNoZeroIntegers(int n) {
    auto valid = [](int x) {
      if (!x) return false;
      while (x) {
        if (x % 10 == 0) return false;
        x /= 10;
      }
      return true;
    };
    
    for (int i = 1; i &lt;= n / 2; ++i)
      if (valid(i) &amp;&amp; valid(n - i)) 
        return {i, n - i};
    return {};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1317-convert-integer-to-the-sum-of-two-no-zero-integers/">花花酱 LeetCode 1317. Convert Integer to the Sum of Two No-Zero Integers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-1317-convert-integer-to-the-sum-of-two-no-zero-integers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1200. Minimum Absolute Difference</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1200-minimum-absolute-difference/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1200-minimum-absolute-difference/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Sep 2019 08:39:20 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[all pairs]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5569</guid>

					<description><![CDATA[<p>Given an&#160;array&#160;of&#160;distinct&#160;integers&#160;arr, find all pairs of elements with the minimum absolute difference of any two elements.&#160; Return a list of pairs in ascending order(with respect&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1200-minimum-absolute-difference/">花花酱 LeetCode 1200. Minimum Absolute Difference</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 an&nbsp;array&nbsp;of&nbsp;<strong>distinct</strong>&nbsp;integers&nbsp;<code>arr</code>, find all pairs of elements with the minimum absolute difference of any two elements.&nbsp;</p>



<p>Return a list of pairs in ascending order(with respect to pairs), each pair&nbsp;<code>[a, b]</code>&nbsp;follows</p>



<ul><li><code>a, b</code>&nbsp;are from&nbsp;<code>arr</code></li><li><code>a &lt; b</code></li><li><code>b - a</code>&nbsp;equals to the minimum absolute difference of any two elements in&nbsp;<code>arr</code></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,2,1,3]
<strong>Output:</strong> [[1,2],[2,3],[3,4]]
<strong>Explanation: </strong>The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,3,6,10,15]
<strong>Output:</strong> [[1,3]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,8,-10,23,19,-4,-14,27]
<strong>Output:</strong> [[-14,-10],[19,23],[23,27]]
</pre>



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



<ul><li><code>2 &lt;= arr.length &lt;= 10^5</code></li><li><code>-10^6 &lt;= arr[i] &lt;= 10^6</code></li></ul>



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



<p>The min abs difference could only happen between consecutive numbers in sorted form.</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:
  vector&lt;vector&lt;int&gt;&gt; minimumAbsDifference(vector&lt;int&gt;&amp; arr) {
    sort(begin(arr), end(arr));
    vector&lt;vector&lt;int&gt;&gt; ans;
    int best = INT_MAX;
    for (int i = 1; i &lt; arr.size(); ++i) {
      int d = abs(arr[i] - arr[i - 1]);      
      if (d &lt; best) {
        ans.clear();
        best = d;
      }
      if (d == best) ans.push_back({arr[i - 1], arr[i]});      
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1200-minimum-absolute-difference/">花花酱 LeetCode 1200. Minimum Absolute Difference</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-1200-minimum-absolute-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 455. Assign Cookies</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-455-assign-cookies/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-455-assign-cookies/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 15 Aug 2018 15:05:13 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3529</guid>

					<description><![CDATA[<p>Problem Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-455-assign-cookies/">花花酱 LeetCode 455. Assign Cookies</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="281" src="https://www.youtube.com/embed/3kJpg7Smc3E?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g<sub>i</sub>, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s<sub>j</sub>. If s<sub>j</sub> &gt;= g<sub>i</sub>, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.</p>
<p><b>Note:</b><br />
You may assume the greed factor is always positive.<br />
You cannot assign more than one cookie to one child.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,2,3], [1,1]

<b>Output:</b> 1

<b>Explanation:</b> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,2], [1,2,3]

<b>Output:</b> 2

<b>Explanation:</b> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
You have 3 cookies and their sizes are big enough to gratify all of the children, 
You need to output 2.
</pre>
<h1>Solution: Greedy + Two Pointers</h1>
<p>Time complexity: O(mlogm + nlogn)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
public:
  int findContentChildren(vector&lt;int&gt;&amp; g, vector&lt;int&gt;&amp; s) {
    sort(begin(g), end(g));
    sort(begin(s), end(s));

    int ans = 0;
    int j = 0;
    for (int i = 0; i &lt; g.size(); ++i) { 
      while (j &lt; s.size() &amp;&amp; s[j] &lt; g[i]) {
        ++j;
      }
      if (j &lt; s.size()) {
        ++ans;
        ++j;
        continue;
      }
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-455-assign-cookies/">花花酱 LeetCode 455. Assign Cookies</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-455-assign-cookies/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
