<?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>monotonic stack Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/monotonic-stack/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/monotonic-stack/</link>
	<description></description>
	<lastBuildDate>Sun, 28 Feb 2021 07:46:40 +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>monotonic stack Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/monotonic-stack/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1776. Car Fleet II</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Feb 2021 07:45:38 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8176</guid>

					<description><![CDATA[<p>There are&#160;n&#160;cars traveling at different speeds in the same direction along a one-lane road. You are given an array&#160;cars&#160;of length&#160;n, where&#160;cars[i] = [positioni, speedi]&#160;represents: positioni&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/">花花酱 LeetCode 1776. Car Fleet II</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 are&nbsp;<code>n</code>&nbsp;cars traveling at different speeds in the same direction along a one-lane road. You are given an array&nbsp;<code>cars</code>&nbsp;of length&nbsp;<code>n</code>, where&nbsp;<code>cars[i] = [position<sub>i</sub>, speed<sub>i</sub>]</code>&nbsp;represents:</p>



<ul><li><code>position<sub>i</sub></code>&nbsp;is the distance between the&nbsp;<code>i<sup>th</sup></code>&nbsp;car and the beginning of the road in meters. It is guaranteed that&nbsp;<code>position<sub>i</sub>&nbsp;&lt; position<sub>i+1</sub></code>.</li><li><code>speed<sub>i</sub></code>&nbsp;is the initial speed of the&nbsp;<code>i<sup>th</sup></code>&nbsp;car in meters per second.</li></ul>



<p>For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the&nbsp;<strong>slowest</strong>&nbsp;car in the fleet.</p>



<p>Return an array&nbsp;<code>answer</code>, where&nbsp;<code>answer[i]</code>&nbsp;is the time, in seconds, at which the&nbsp;<code>i<sup>th</sup></code>&nbsp;car collides with the next car, or&nbsp;<code>-1</code>&nbsp;if the car does not collide with the next car. Answers within&nbsp;<code>10<sup>-5</sup></code>&nbsp;of the actual answers are accepted.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cars = [[1,2],[2,1],[4,3],[7,2]]
<strong>Output:</strong> [1.00000,-1.00000,3.00000,-1.00000]
<strong>Explanation:</strong> After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cars = [[3,4],[5,4],[6,3],[9,1]]
<strong>Output:</strong> [2.00000,1.00000,1.50000,-1.00000]
</pre>



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



<ul><li><code>1 &lt;= cars.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= position<sub>i</sub>, speed<sub>i</sub>&nbsp;&lt;= 10<sup>6</sup></code></li><li><code>position<sub>i</sub>&nbsp;&lt; position<sub>i+1</sub></code></li></ul>



<h2><strong>Solution: Monotonic Stack</strong></h2>



<p>Key observation: If my speed is slower than the speed of the previous car, not only mine but also all cars behind me will NEVER be able to catch/collide with the previous car. Such that we can throw it away.</p>



<p>Maintain a stack that stores the indices of cars with increasing speed.</p>



<p>Process car from right to left, for each car, pop the stack (throw the fastest car away) if any of the following conditions hold.<br>1)  speed &lt;= stack.top().speed<br>2) There are more than one car before me and it takes more than to collide the fastest car than time the fastest took to collide.</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:
  vector&lt;double&gt; getCollisionTimes(vector&lt;vector&lt;int&gt;&gt;&amp; cars) {
    auto collide = [&amp;](int i, int j) -&gt; double {
      return static_cast&lt;double&gt;(cars[i][0] - cars[j][0]) /
        (cars[j][1] - cars[i][1]);
    };
    const int n = cars.size();
    vector&lt;double&gt; ans(n, -1);
    stack&lt;int&gt; s;
    for (int i = n - 1; i &gt;= 0; --i) {
      while (!s.empty() &amp;&amp; (cars[i][1] &lt;= cars[s.top()][1] ||
                           (s.size() &gt; 1 &amp;&amp; collide(i, s.top()) &gt; ans[s.top()])))
        s.pop();
      ans[i] = s.empty() ? -1 : collide(i, s.top());
      s.push(i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1776-car-fleet-ii/">花花酱 LeetCode 1776. Car Fleet II</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/stack/leetcode-1776-car-fleet-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 13 Jun 2020 17:04:18 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6901</guid>

					<description><![CDATA[<p>Given the array&#160;prices&#160;where&#160;prices[i]&#160;is the price of the&#160;ith&#160;item in a shop. There is a special discount for items in the shop, if you buy the&#160;ith&#160;item, then&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/">花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</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="花花酱 LeetCode1475. Final Prices With a Special Discount in a Shop  - 刷题找工作 EP334" width="500" height="375" src="https://www.youtube.com/embed/X98Yc4YtgyA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the array&nbsp;<code>prices</code>&nbsp;where&nbsp;<code>prices[i]</code>&nbsp;is the price of the&nbsp;<code>ith</code>&nbsp;item in a shop. There is a special discount for items in the shop, if you buy the&nbsp;<code>ith</code>&nbsp;item, then you will receive a discount equivalent to&nbsp;<code>prices[j]</code>&nbsp;where&nbsp;<code>j</code>&nbsp;is the&nbsp;<strong>minimum</strong>&nbsp;index such that&nbsp;<code>j &gt; i</code>&nbsp;and&nbsp;<code>prices[j] &lt;= prices[i]</code>, otherwise, you will not receive any discount at all.</p>



<p><em>Return an array where the&nbsp;<code>ith</code>&nbsp;element is the final price you will pay for the&nbsp;<code>ith</code>&nbsp;item of the shop considering the special discount.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [8,4,6,2,3]
<strong>Output:</strong> [4,2,4,2,3]
<strong>Explanation:</strong>&nbsp;
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.&nbsp;
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.&nbsp;
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.&nbsp;
For items 3 and 4 you will not receive any discount at all.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [1,2,3,4,5]
<strong>Output:</strong> [1,2,3,4,5]
<strong>Explanation:</strong> In this case, for all items, you will not receive any discount at all.
</pre>



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



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



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



<ul><li><code>1 &lt;= prices.length &lt;= 500</code></li><li><code>1 &lt;= prices[i] &lt;= 10^3</code></li></ul>



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



<p>Time complexity: O(n^2)<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; finalPrices(vector&lt;int&gt; prices) {
    const int n = prices.size();
    for (int i = 0; i &lt; n; ++i)      
      for (int j = i + 1; j &lt; n; ++j)
        if (prices[j] &lt;= prices[i]) {
          prices[i] -= prices[j];
          break;
        }     
    return prices;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Monotonic Stack</strong></h2>



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



<p>Use a stack to store monotonically increasing items, when the current item is cheaper than the top of the stack, we get the discount and pop that item. Repeat until the current item is no longer cheaper or the stack becomes empty.</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:
  vector&lt;int&gt; finalPrices(vector&lt;int&gt; prices) {
    // stores pointers of monotonically incraseing elements.
    stack&lt;int*&gt; s; 
    for (int&amp; p : prices) {
      while (!s.empty() &amp;&amp; *s.top() &gt;= p) {
        *s.top() -= p;
        s.pop();
      }
      s.push(&amp;p);
    }      
    return prices;
  }
};</pre>
</div></div>



<p>index version</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; finalPrices(vector&lt;int&gt; prices) {
    // stores indices of monotonically incraseing elements.
    stack&lt;int&gt; s; 
    for (int i = 0; i &lt; prices.size(); ++i) {
      while (!s.empty() &amp;&amp; prices[s.top()] &gt;= prices[i]) {
        prices[s.top()] -= prices[i];
        s.pop();
      }
      s.push(i);
    }      
    return prices;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/">花花酱 LeetCode 1475. Final Prices With a Special Discount in a Shop</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/stack/leetcode-1475-final-prices-with-a-special-discount-in-a-shop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 84. Largest Rectangle in Histogram</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 14 Feb 2020 08:14:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic stack]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6313</guid>

					<description><![CDATA[<p>Given&#160;n&#160;non-negative integers representing the histogram&#8217;s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/">花花酱 LeetCode 84. Largest Rectangle in Histogram</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;<em>n</em>&nbsp;non-negative integers representing the histogram&#8217;s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/10/12/histogram.png" alt=""/></figure>



<p><br>Above is a histogram where width of each bar is 1, given height =&nbsp;<code>[2,1,5,6,2,3]</code>.</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/10/12/histogram_area.png" alt=""/></figure>



<p><br>The largest rectangle is shown in the shaded area, which has area =&nbsp;<code>10</code>&nbsp;unit.</p>



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



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



<h2><strong>Solution 1: Monotonic Stack</strong></h2>



<p>Use a monotonic stack to maintain the higher bars&#8217;s indices in ascending order.<br>When encounter a lower bar, pop the tallest bar and use it as the bottleneck to compute the area.</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, 12ms, 10.7MB
class Solution {
public:
  int largestRectangleArea(vector&lt;int&gt;&amp; heights) {
    heights.push_back(0);
    const int n = heights.size();
    stack&lt;int&gt; s;
    int ans = 0;
    int i = 0;
    while (i &lt; n) {
      if (s.empty() || heights[i] &gt;= heights[s.top()]) {
        s.push(i++);
      } else {
        int h = heights[s.top()]; s.pop();
        int w = s.empty() ? i : i - s.top() - 1;        
        ans = max(ans, h * w);
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-84-largest-rectangle-in-histogram/">花花酱 LeetCode 84. Largest Rectangle in Histogram</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/stack/leetcode-84-largest-rectangle-in-histogram/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
