<?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>max Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/max/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/max/</link>
	<description></description>
	<lastBuildDate>Sat, 23 Jan 2021 19:28:14 +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>max Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/max/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode1732. Find the Highest Altitude</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode1732-find-the-highest-altitude/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode1732-find-the-highest-altitude/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 23 Jan 2021 19:27:40 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[max]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8003</guid>

					<description><![CDATA[<p>There is a biker going on a road trip. The road trip consists of&#160;n + 1&#160;points at different altitudes. The biker starts his trip on&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode1732-find-the-highest-altitude/">花花酱 LeetCode1732. Find the Highest Altitude</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 biker going on a road trip. The road trip consists of&nbsp;<code>n + 1</code>&nbsp;points at different altitudes. The biker starts his trip on point&nbsp;<code>0</code>&nbsp;with altitude equal&nbsp;<code>0</code>.</p>



<p>You are given an integer array&nbsp;<code>gain</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where&nbsp;<code>gain[i]</code>&nbsp;is the&nbsp;<strong>net gain in altitude</strong>&nbsp;between points&nbsp;<code>i</code>​​​​​​ and&nbsp;<code>i + 1</code>&nbsp;for all (<code>0 &lt;= i &lt; n)</code>. Return&nbsp;<em>the&nbsp;<strong>highest altitude</strong>&nbsp;of a point.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> gain = [-5,1,5,0,-7]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> gain = [-4,-3,-2,-1,4,3,2]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
</pre>



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



<ul><li><code>n == gain.length</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li><code>-100 &lt;= gain[i] &lt;= 100</code></li></ul>



<h2><strong>Solution: Running Max</strong></h2>



<p>Time complexity: O(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 largestAltitude(vector&lt;int&gt;&amp; gain) {
    int ans = 0;
    int cur = 0;
    for (int diff : gain)
      ans = max(ans, cur += diff);
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode1732-find-the-highest-altitude/">花花酱 LeetCode1732. Find the Highest Altitude</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/leetcode1732-find-the-highest-altitude/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1323. Maximum 69 Number</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 21 Jan 2020 02:57:05 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6120</guid>

					<description><![CDATA[<p>Given a positive integer&#160;num&#160;consisting only of digits 6 and 9. Return the maximum number you can get by changing&#160;at most&#160;one digit (6 becomes 9, and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/">花花酱 LeetCode 1323. Maximum 69 Number</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 a positive integer&nbsp;<code>num</code>&nbsp;consisting only of digits 6 and 9.</p>



<p>Return the maximum number you can get by changing&nbsp;<strong>at most</strong>&nbsp;one digit (6 becomes 9, and 9 becomes 6).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9669
<strong>Output:</strong> 9969
<strong>Explanation:</strong> 
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.&nbsp;
The maximum number is 9969.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9996
<strong>Output:</strong> 9999
<strong>Explanation:</strong> Changing the last digit 6 to 9 results in the maximum number.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9999
<strong>Output:</strong> 9999
<strong>Explanation:</strong> It is better not to apply any change.</pre>



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



<ul><li><code>1 &lt;= num &lt;= 10^4</code></li><li><code>num</code>&#8216;s digits are 6 or 9.</li></ul>



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



<p>Replace the highest 6 to 9, if no 6, return the original number.</p>



<p>Time complexity: O(1)<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 maximum69Number (int num) {
    string s = to_string(num);
    for (int i = 0; i &lt; s.length(); ++i) {
      if (s[i] == '6') {
        s[i] = '9';
        return stoi(s);
      }
    }
    return num;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/">花花酱 LeetCode 1323. Maximum 69 Number</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-1323-maximum-69-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 628. Maximum Product of Three Numbers</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-628-maximum-product-of-three-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Aug 2018 05:02:31 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[priority_queue]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[topk]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3594</guid>

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

					<description><![CDATA[<p>Problem https://leetcode.com/problems/third-maximum-number/description/ Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/">花花酱 LeetCode 414. Third Maximum Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/third-maximum-number/description/">https://leetcode.com/problems/third-maximum-number/description/</a></p>
<p>Given a <b>non-empty</b> array of integers, return the <b>third</b> maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [3, 2, 1]

<b>Output:</b> 1

<b>Explanation:</b> The third maximum is 1.
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> [1, 2]

<b>Output:</b> 2

<b>Explanation:</b> The third maximum does not exist, so the maximum (2) is returned instead.
</pre>
<p><b>Example 3:</b></p>
<pre class="crayon:false "><b>Input:</b> [2, 2, 3, 1]

<b>Output:</b> 1

<b>Explanation:</b> Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.</pre>
<h1><strong>Solution: Set</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  int thirdMax(vector&lt;int&gt;&amp; nums) {
    set&lt;int&gt; s;
    for (int num : nums) {
      s.insert(num);
      if (s.size() &gt; 3) s.erase(s.begin());
    }
    return s.size() != 3 ? *s.rbegin() : *s.begin();
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 52 ms
"""
class Solution:
  def thirdMax(self, nums):
    s = set()
    for num in nums:
      s.add(num)
      if len(s) &gt; 3: s.remove(min(s))
    return min(s) if len(s) == 3 else max(s)</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/">花花酱 LeetCode 414. Third Maximum Number</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-414-third-maximum-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 53. Maximum Subarray</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-53-maximum-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-53-maximum-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 28 Nov 2017 05:07:38 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[max]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=949</guid>

					<description><![CDATA[<p>Problem: Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-53-maximum-subarray/">花花酱 LeetCode 53. Maximum Subarray</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/7J5rs56JBs8?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Find the contiguous subarray within an array (containing at least one number) which has the largest sum.</p>
<p>For example, given the array <code>[-2,1,-3,4,-1,2,1,-5,4]</code>,<br />
the contiguous subarray <code>[4,-1,2,1]</code> has the largest sum = <code>6</code>.</p>
<p><strong>Idea:</strong></p>
<p>DP</p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms (better than 98.66%)
class Solution {
public:
    int maxSubArray(vector&lt;int&gt;&amp; nums) {
        vector&lt;int&gt; f(nums.size());
        f[0] = nums[0];
        
        for (int i = 1; i &lt; nums.size(); ++i)
            f[i] = max(f[i - 1] + nums[i], nums[i]);
        
        return *std::max_element(f.begin(), f.end());
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-53-maximum-subarray/">花花酱 LeetCode 53. Maximum Subarray</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-53-maximum-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 699. Falling Squares</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-699-falling-squares/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-699-falling-squares/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 25 Oct 2017 03:09:00 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[height]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[range]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=693</guid>

					<description><![CDATA[<p>题目大意：方块落下后会堆叠在重叠的方块之上，问每一块方块落下之后最高的方块的高度是多少？ Problem: On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th square dropped (positions[i] = (left, side_length))&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-699-falling-squares/">花花酱 LeetCode 699. Falling Squares</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/UeuV-6Ygxs4?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：方块落下后会堆叠在重叠的方块之上，问每一块方块落下之后最高的方块的高度是多少？</p>
<p><strong>Problem:</strong></p>
<p>On an infinite number line (x-axis), we drop given squares in the order they are given.</p>
<p>The <code>i</code>-th square dropped (<code>positions[i] = (left, side_length)</code>) is a square with the left-most point being <code>positions[i][0]</code> and sidelength <code>positions[i][1]</code>.</p>
<p>The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares. We wait for each square to stick before dropping the next.</p>
<p>The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square). Squares dropped adjacent to each other will not stick together prematurely.</p>
<p>&nbsp;</p>
<p>Return a list <code>ans</code> of heights. Each height <code>ans[i]</code> represents the current highest height of any square we have dropped, after dropping squares represented by <code>positions[0], positions[1], ..., positions[i]</code>.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: [[1, 2], [2, 3], [6, 1]]
Output: [2, 5, 5]
Explanation:

After the first drop of 
positions[0] = [1, 2]:
_aa
_aa
-------
The maximum height of any square is 2.


After the second drop of 
positions[1] = [2, 3]:
__aaa
__aaa
__aaa
_aa__
_aa__
--------------
The maximum height of any square is 5.  
The larger square stays on top of the smaller square despite where its center
of gravity is, because squares are infinitely sticky on their bottom edge.


After the third drop of 
positions[1] = [6, 1]:
__aaa
__aaa
__aaa
_aa
_aa___a
--------------
The maximum height of any square is still 5.

Thus, we return an answer of 
[2, 5, 5]</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: [[100, 100], [200, 100]]
Output: [100, 100]
Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.</pre><p><b>Note:</b></p>
<p>&nbsp;</p>
<ul>
<li><code>1 &lt;= positions.length &lt;= 1000</code>.</li>
<li><code>1 &lt;= positions[i][0] &lt;= 10^8</code>.</li>
<li><code>1 &lt;= positions[i][1] &lt;= 10^6</code>.</li>
</ul>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Range query with map</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1.png"><img class="alignnone size-full wp-image-701" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2.png"><img class="alignnone size-full wp-image-700" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/699-ep97-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><strong>Solution:</strong></p>
<p>C++ map</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 29 ms
class Solution {
public:
    vector&lt;int&gt; fallingSquares(vector&lt;pair&lt;int, int&gt;&gt;&amp; positions) {
        vector&lt;int&gt; ans;
        map&lt;pair&lt;int, int&gt;, int&gt; b; // {{start, end}, height}        
        int maxHeight = INT_MIN;
        for (const auto&amp; kv: positions) {
            int start = kv.first;
            int size = kv.second;
            int end = start + size;
            // first range intersect with new_interval
            auto it = b.upper_bound({start, end});
            if (it != b.begin()) {
                auto it2 = it;
                if ((--it2)-&gt;first.second &gt; start) it = it2;
            }
            
            int baseHeight = 0;
            vector&lt;tuple&lt;int, int, int&gt;&gt; ranges;
            while (it != b.end() &amp;&amp; it-&gt;first.first &lt; end) {
                const int s = it-&gt;first.first;
                const int e = it-&gt;first.second;
                const int h = it-&gt;second;
                if (s &lt; start) ranges.emplace_back(s, start, h);
                if (e &gt; end) ranges.emplace_back(end, e, h);
                // max height of intesected ranges
                baseHeight = max(baseHeight, h);
                it = b.erase(it);
            }
            
            int newHeight = size + baseHeight;
            
            b[{start, end}] = newHeight;
            
            for (const auto&amp; range: ranges)
                b[{get&lt;0&gt;(range), get&lt;1&gt;(range)}] = get&lt;2&gt;(range);
            
            maxHeight = max(maxHeight, newHeight);            
            ans.push_back(maxHeight);
        }
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>C++ vector without merge</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 46 ms
class Solution {
public:
    vector&lt;int&gt; fallingSquares(vector&lt;pair&lt;int, int&gt;&gt;&amp; positions) {
        vector&lt;int&gt; ans;
        vector&lt;Interval&gt; intervals;
        int maxHeight = INT_MIN;
        for (const auto&amp; kv: positions) {
            int start = kv.first;
            int end = start + kv.second;            
            int baseHeight = 0;
            for (const Interval&amp; interval : intervals) {
                if (interval.start &gt;= end || interval.end &lt;= start)             
                    continue;
                baseHeight = max(baseHeight, interval.height);
            }
            int height = kv.second + baseHeight;
            intervals.push_back(Interval(start, end, height));
            maxHeight = max(maxHeight, height);
            ans.push_back(maxHeight);
        }
        return ans;
    }
private:
    struct Interval {
        int start;
        int end;
        int height;
        Interval(int start, int end, int height) 
            : start(start), end(end), height(height) {}
    };
};</pre><p>C++ / vector with merge (slower)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 86 ms
class Solution {
public:
    vector&lt;int&gt; fallingSquares(vector&lt;pair&lt;int, int&gt;&gt;&amp; positions) {
        vector&lt;int&gt; ans;
        vector&lt;Interval&gt; intervals;
        int maxHeight = INT_MIN;
        for (const auto&amp; kv: positions) {
            vector&lt;Interval&gt; tmp;
            int start = kv.first;
            int end = start + kv.second;            
            int baseHeight = 0;
            for (const Interval&amp; interval : intervals) {
                if (interval.start &gt;= end || interval.end &lt;= start) {
                    tmp.push_back(interval);                
                    continue;
                }
                baseHeight = max(baseHeight, interval.height);
                if (interval.start &lt; start || interval.end &gt; end)
                    tmp.push_back(interval);
            }
            int height = kv.second + baseHeight;
            tmp.push_back(Interval(start, end, height));
            intervals.swap(tmp);
            maxHeight = max(maxHeight, height);
            ans.push_back(maxHeight);
        }
        return ans;
    }
private:
    struct Interval {
        int start;
        int end;
        int height;
        Interval(int start, int end, int height) 
            : start(start), end(end), height(height) {}
    };
};</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/data-structure/leetcode-715-range-module/">[解题报告] LeetCode 715. Range Module</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-218-the-skyline-problem/">[解题报告] LeetCode 218. The Skyline Problem</a></li>
<li>[解题报告] LeetCode 57. Insert Interval</li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-699-falling-squares/">花花酱 LeetCode 699. Falling Squares</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/geometry/leetcode-699-falling-squares/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 221. Maximal Square</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-221-maximal-square/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-221-maximal-square/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 19 Sep 2017 02:53:13 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=339</guid>

					<description><![CDATA[<p>Problem: Given a 2D binary matrix filled with 0&#8217;s and 1&#8217;s, find the largest square containing only 1&#8217;s and return its area. For example, given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-221-maximal-square/">花花酱 LeetCode 221. Maximal Square</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/vkFUB--OYy0?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a 2D binary matrix filled with 0&#8217;s and 1&#8217;s, find the largest square containing only 1&#8217;s and return its area.</p>
<p>For example, given the following matrix:</p>
<p>1 0 1 0 0<br />
1 0 <span style="color: red;">1</span> <span style="color: red;">1</span> 1<br />
1 1 <span style="color: red;">1</span> <span style="color: red;">1</span> 1<br />
1 0 0 1 0</p>
<p>Return 4.</p>
<p>&nbsp;</p>
<p><strong>Idea:</strong></p>
<p>Dynamic programming</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p>Solution 0: O(n^5)</p>
<p>&nbsp;</p>
<p><a style="font-size: 1rem; color: #0f3647;" href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1.png"><img class="alignnone size-full wp-image-344" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>Solution 1: O(n^3)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2.png"><img class="alignnone size-full wp-image-343" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a style="font-size: 1rem;" href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3.png"><img class="alignnone size-full wp-image-342" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-3-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>Solution 2: O(n^2)</p>
<p><img class="alignnone size-full wp-image-341" style="font-size: 1rem;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-4.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-4-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/221-ep62-4-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>&nbsp;</p>
<p><strong>Solution 1:</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Time complexity: O(n^3)
// Running time: 39 ms
class Solution {
public:
    int maximalSquare(vector&lt;vector&lt;char&gt;&gt;&amp; matrix) {
        if (matrix.empty()) return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        
        // sums[i][j] = sum(matrix[0][0] ~ matrix[i-1][j-1])
        vector&lt;vector&lt;int&gt;&gt; sums(m + 1, vector&lt;int&gt;(n + 1, 0));
        for (int i = 1; i &lt;= m; ++i)
            for (int j = 1; j &lt;= n; ++j)        
                sums[i][j] = matrix[i - 1][j - 1] - '0' 
                             + sums[i - 1][j]
                             + sums[i][j - 1]
                             - sums[i - 1][j - 1];
        
        int ans = 0;
        for (int i = 1; i &lt;= m; ++i)
            for (int j = 1; j &lt;= n; ++j)
                for (int k = min(m - i + 1, n - j + 1); k &gt; 0; --k) {
                    int sum = sums[i + k - 1][j + k - 1]
                            - sums[i + k - 1][j - 1]
                            - sums[i - 1][j + k - 1]
                            + sums[i - 1][j - 1];
                    // full of 1
                    if (sum == k*k) {
                        ans = max(ans, sum);
                        break;
                    }
                }

        return ans;
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 2:</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Time complexity: O(n^2)
// Running time: 6 ms
class Solution {
public:
    int maximalSquare(vector&lt;vector&lt;char&gt;&gt;&amp; matrix) {
        if (matrix.empty()) return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        
        vector&lt;vector&lt;int&gt;&gt; sizes(m, vector&lt;int&gt;(n, 0));
        
        int ans = 0;
        
        for (int i = 0; i &lt; m; ++i)
            for (int j = 0; j &lt; n; ++j) {
                sizes[i][j] = matrix[i][j] - '0';
                if (!sizes[i][j]) continue;                            
                
                if (i == 0 || j == 0) {
                    // do nothing
                } else if (i == 0)
                    sizes[i][j] = sizes[i][j - 1] + 1;
                else if (j == 0)
                    sizes[i][j] = sizes[i - 1][j] + 1;
                else
                    sizes[i][j] = min(min(sizes[i - 1][j - 1], 
                                          sizes[i - 1][j]),
                                          sizes[i][j - 1]) + 1;
                
                ans = max(ans, sizes[i][j]*sizes[i][j]);
            }
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-221-maximal-square/">花花酱 LeetCode 221. Maximal Square</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-221-maximal-square/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
