<?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 Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/monotonic/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/monotonic/</link>
	<description></description>
	<lastBuildDate>Thu, 30 Jan 2020 05:48:57 +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 Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/monotonic/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 975. Odd Even Jump</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-975-odd-even-jump/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-975-odd-even-jump/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 16 Jan 2019 04:44:12 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4648</guid>

					<description><![CDATA[<p>You are given an integer array&#160;A.&#160; From&#160;some starting index, you can make a series of jumps.&#160; The (1st, 3rd, 5th, &#8230;)&#160;jumps in the series are&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-975-odd-even-jump/">花花酱 LeetCode 975. Odd Even Jump</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 width="500" height="375" src="https://www.youtube.com/embed/MEqDu4hA_Wo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an integer array&nbsp;<code>A</code>.&nbsp; From&nbsp;some starting index, you can make a series of jumps.&nbsp; The (1st, 3rd, 5th, &#8230;)&nbsp;jumps in the series are called&nbsp;<em>odd numbered jumps</em>, and the (2nd, 4th, 6th, &#8230;) jumps in the series are called&nbsp;<em>even numbered jumps</em>.</p>



<p>You may from index&nbsp;<code>i</code>&nbsp;jump forward to index&nbsp;<code>j</code>&nbsp;(with&nbsp;<code>i&nbsp;&lt; j</code>) in the following way:</p>



<ul><li>During odd numbered jumps (ie. jumps 1, 3, 5, &#8230;), you jump to the index&nbsp;j&nbsp;such that&nbsp;<code>A[i] &lt;= A[j]</code>&nbsp;and&nbsp;<code>A[j]</code>&nbsp;is the smallest possible value.&nbsp; If there are multiple such indexes&nbsp;<code>j</code>, you can only jump to the&nbsp;<strong>smallest</strong>&nbsp;such index&nbsp;<code>j</code>.</li><li>During even numbered jumps (ie. jumps 2, 4, 6, &#8230;), you jump to the index&nbsp;j&nbsp;such that&nbsp;<code>A[i] &gt;= A[j]</code>&nbsp;and&nbsp;<code>A[j]</code>&nbsp;is the largest&nbsp;possible value.&nbsp; If there are multiple such indexes&nbsp;<code>j</code>, you can only jump to the&nbsp;<strong>smallest</strong>&nbsp;such index&nbsp;<code>j</code>.</li><li>(It may be the case that for some index&nbsp;<code>i,</code>&nbsp;there are no legal jumps.)</li></ul>



<p>A starting index is&nbsp;<em>good</em>&nbsp;if, starting from that index, you can reach the end of the array (index&nbsp;<code>A.length - 1</code>) by jumping some number of times (possibly 0 or more than once.)</p>



<p>Return the number of good starting indexes.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[10,13,12,14,15] <br><strong>Output: </strong>2 </pre>



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



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



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



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



<p><strong>Note:</strong></p>



<ol><li><code>1 &lt;= A.length &lt;= 20000</code></li><li><code>0 &lt;= A[i] &lt; 100000</code></li></ol>



<h2>Solution: Binary Search + DP</h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-1.png" alt="" class="wp-image-4652" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-2.png" alt="" class="wp-image-4653" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/01/975-ep241-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<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">class Solution {
public:
  int oddEvenJumps(vector&lt;int&gt;&amp; A) {
    const int n = A.size();
    map&lt;int, int&gt; m;
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(2));
    dp[n - 1][0] = dp[n - 1][1] = 1;
    m[A[n - 1]] = n - 1;
    int ans = 1;
    for (int i = n - 2; i &gt;= 0; --i) {
      auto o = m.lower_bound(A[i]);
      if (o != m.end()) dp[i][0] = dp[o-&gt;second][1];
      auto e = m.upper_bound(A[i]);
      if (e != m.begin()) dp[i][1] = dp[prev(e)-&gt;second][0];
      if (dp[i][0]) ++ans;
      m[A[i]] = i;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-975-odd-even-jump/">花花酱 LeetCode 975. Odd Even Jump</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-975-odd-even-jump/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 901. Online Stock Span</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-901-online-stock-span/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-901-online-stock-span/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 14 Sep 2018 20:20:35 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[monotonic]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3969</guid>

					<description><![CDATA[<p>Problem Write a class&#160;StockSpanner&#160;which collects daily price quotes for some stock, and returns the&#160;span&#160;of that stock&#8217;s price for the current day. The span of the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-901-online-stock-span/">花花酱 LeetCode 901. Online Stock Span</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 901. Online Stock Span - 刷题找工作 EP224" width="500" height="375" src="https://www.youtube.com/embed/RGRC46zHB98?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>


<h1><strong>Problem</strong></h1>
<p>Write a class&nbsp;<code>StockSpanner</code>&nbsp;which collects daily price quotes for some stock, and returns the&nbsp;<em>span</em>&nbsp;of that stock&#8217;s price for the current day.</p>
<p>The span of the stock&#8217;s price today&nbsp;is defined as the maximum number of consecutive days (starting from today and going backwards)&nbsp;for which the price of the stock was less than or equal to today&#8217;s price.</p>
<p>For example, if the price of a stock over the next 7 days were&nbsp;<code>[100, 80, 60, 70, 60, 75, 85]</code>, then the stock spans would be&nbsp;<code>[1, 1, 1, 2, 1, 4, 6]</code>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">["StockSpanner","next","next","next","next","next","next","next"]</span>, <span id="example-input-1-2">[[],[100],[80],[60],[70],[60],[75],[85]]</span>
<strong>Output: </strong><span id="example-output-1">[null,1,1,1,2,1,4,6]</span>
<strong>Explanation: </strong>
First, S = StockSpanner() is initialized.  Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.

Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.
</pre>
<p><strong>Note:</strong></p>
<ol>
<li>Calls to&nbsp;<code>StockSpanner.next(int price)</code>&nbsp;will have&nbsp;<code>1 &lt;= price &lt;= 10^5</code>.</li>
<li>There will be at most&nbsp;<code>10000</code>&nbsp;calls to&nbsp;<code>StockSpanner.next</code>&nbsp;per test case.</li>
<li>There will be at most&nbsp;<code>150000</code>&nbsp;calls to&nbsp;<code>StockSpanner.next</code>&nbsp;across all test cases.</li>
<li>The total&nbsp;time limit for this problem has been reduced by 75% for&nbsp;C++, and 50% for all other languages.</li>
</ol>
<p><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">&nbsp;</ins></p>
<h1><img class="alignnone size-full wp-image-4003" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/901-ep224-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/901-ep224-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/901-ep224-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/901-ep224-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution 1: Brute Force (TLE)</strong></h1>
<p>Time complexity: O(n) per next call</p>
<p>Space complexity: O(n)</p>
<h1><strong>Solution 2: DP</strong></h1>
<p>dp[i] := span of prices[i]</p>
<p>j = i &#8211; 1<br>
while j &gt;= 0 and prices[i] &gt;= prices[j]: j -= dp[j]<br>
dp[i] = i &#8211; j</p>
<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 144 ms
class StockSpanner {
public:
  StockSpanner() {}

  int next(int price) {
    if (prices_.empty() || price &lt; prices_.back()) {
      dp_.push_back(1);      
    } else {
      int j = prices_.size() - 1;
      while (j &gt;= 0 &amp;&amp; price &gt;= prices_[j]) {
        j -= dp_[j];
      }
      dp_.push_back(prices_.size() - j);
    }    
    prices_.push_back(price);    
    return dp_.back();
  }
private:
  vector&lt;int&gt; dp_;
  vector&lt;int&gt; prices_;  
};</pre>
</div></div>
<h1><strong>Solution 3: Monotonic Stack</strong></h1>
<p>Maintain a monotonic stack whose element are pairs of &lt;price, span&gt;, sorted by price from high to low.</p>
<p>When a new price comes in</p>
<ol>
<li>If it&#8217;s less than top price, add a new pair (price, 1) to the stack, return 1</li>
<li>If it&#8217;s greater than top element, collapse the stack and accumulate the span until the top price is higher than the new price. return the total span</li>
</ol>
<p>e.g. prices: 10, 6, 5, 4, 3, 7</p>
<p>after 3, the stack looks [(10,1), (6,1), (5,1), (4,1), (3, 1)],</p>
<p>when 7 arrives,&nbsp;[(10,1), <del>(6,1), (5,1), (4,1), (3, 1),</del> (7, 4 + 1)] = [(10, 1), (7, 5)]</p>
<p>Time complexity: O(1) amortized, each element will be pushed on to stack once, and pop at most once.</p>
<p>Space complexity: O(n), in the worst case, the prices is in descending order.</p>
<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class StockSpanner {
public:
  StockSpanner() {}

  int next(int price) {
    int span = 1;
    while (!s_.empty() &amp;&amp; price &gt;= s_.top().first) {
      span += s_.top().second;  
      s_.pop();
    }
    s_.emplace(price, span);
    return span;
  }
private:
  stack&lt;pair&lt;int, int&gt;&gt; s_; // {price, span}, ordered by price DESC.
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class StockSpanner {
  private Stack&lt;Integer&gt; prices;
  private Stack&lt;Integer&gt; spans;
  public StockSpanner() {
    prices = new Stack&lt;&gt;();
    spans = new Stack&lt;&gt;();
  }

  public int next(int price) {
    int span = 1;
    while (!prices.empty() &amp;&amp; price &gt;= prices.peek()) {
      span += spans.pop();
      prices.pop();
    }
    prices.push(price);
    spans.push(span);
    return span;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class StockSpanner:
  def __init__(self):
    self.s = list()

  def next(self, price):
    span = 1
    while self.s and price &gt;= self.s[-1][0]:
      span += self.s[-1][1]
      self.s.pop()
    self.s.append((price, span))
    return span</pre>
</div></div>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/simulation/leetcode-735-asteroid-collision/">花花酱 LeetCode 735. Asteroid Collision</a></li>
<li><a href="https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</a></li>
</ul><p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-901-online-stock-span/">花花酱 LeetCode 901. Online Stock Span</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-901-online-stock-span/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 896. Monotonic Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-896-monotonic-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-896-monotonic-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Sep 2018 05:31:07 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[decresing]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[incresing]]></category>
		<category><![CDATA[monotonic]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3798</guid>

					<description><![CDATA[<p>An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i &#60;= j, A[i] &#60;= A[j].  An array A is monotone&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-896-monotonic-array/">花花酱 LeetCode 896. Monotonic 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>An array is <em>monotonic</em> if it is either monotone increasing or monotone decreasing.</p>
<p>An array <code>A</code> is monotone increasing if for all <code>i &lt;= j</code>, <code>A[i] &lt;= A[j]</code>.  An array <code>A</code> is monotone decreasing if for all <code>i &lt;= j</code>, <code>A[i] &gt;= A[j]</code>.</p>
<p>Return <code>true</code> if and only if the given array <code>A</code> is monotonic.</p>
<h1><strong>Solution: </strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isMonotonic(vector&lt;int&gt;&amp; A) {
    bool inc = true;
    bool dec = true;
    
    for (int i = 1; i &lt; A.size(); ++i) {
      inc &amp;= A[i] &gt;= A[i - 1];
      dec &amp;= A[i] &lt;= A[i - 1];
    }
    
    return inc || dec;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
  public boolean isMonotonic(int[] A) {
    boolean inc = true;
    boolean dec = true;
    
    for (int i = 1; i &lt; A.length; ++i) {
      inc &amp;= A[i] &gt;= A[i - 1];
      dec &amp;= A[i] &lt;= A[i - 1];
    }
    
    return inc || dec;
  }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def isMonotonic(self, A):    
    inc = True;
    dec = True;
    
    for i in range(1, len(A)):
      inc = inc and A[i] &gt;= A[i - 1]
      dec = dec and A[i] &lt;= A[i - 1]    
    
    return inc or dec;</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-896-monotonic-array/">花花酱 LeetCode 896. Monotonic 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-896-monotonic-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
