{"id":3969,"date":"2018-09-14T13:20:35","date_gmt":"2018-09-14T20:20:35","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=3969"},"modified":"2020-01-29T21:48:57","modified_gmt":"2020-01-30T05:48:57","slug":"leetcode-901-online-stock-span","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/dynamic-programming\/leetcode-901-online-stock-span\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 901. Online Stock Span"},"content":{"rendered":"\n<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\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 901. Online Stock Span - \u5237\u9898\u627e\u5de5\u4f5c EP224\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/RGRC46zHB98?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n<h1><strong>Problem<\/strong><\/h1>\n<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>\n<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>\n<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>\n<p><strong>Example 1:<\/strong><\/p>\n<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>\n<strong>Output: <\/strong><span id=\"example-output-1\">[null,1,1,1,2,1,4,6]<\/span>\n<strong>Explanation: <\/strong>\nFirst, S = StockSpanner() is initialized.  Then:\nS.next(100) is called and returns 1,\nS.next(80) is called and returns 1,\nS.next(60) is called and returns 1,\nS.next(70) is called and returns 2,\nS.next(60) is called and returns 1,\nS.next(75) is called and returns 4,\nS.next(85) is called and returns 6.\n\nNote that (for example) S.next(75) returned 4, because the last 4 prices\n(including today's price of 75) were less than or equal to today's price.\n<\/pre>\n<p><strong>Note:<\/strong><\/p>\n<ol>\n<li>Calls to&nbsp;<code>StockSpanner.next(int price)<\/code>&nbsp;will have&nbsp;<code>1 &lt;= price &lt;= 10^5<\/code>.<\/li>\n<li>There will be at most&nbsp;<code>10000<\/code>&nbsp;calls to&nbsp;<code>StockSpanner.next<\/code>&nbsp;per test case.<\/li>\n<li>There will be at most&nbsp;<code>150000<\/code>&nbsp;calls to&nbsp;<code>StockSpanner.next<\/code>&nbsp;across all test cases.<\/li>\n<li>The total&nbsp;time limit for this problem has been reduced by 75% for&nbsp;C++, and 50% for all other languages.<\/li>\n<\/ol>\n<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>\n<h1><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/h1>\n<h1><strong>Solution 1: Brute Force (TLE)<\/strong><\/h1>\n<p>Time complexity: O(n) per next call<\/p>\n<p>Space complexity: O(n)<\/p>\n<h1><strong>Solution 2: DP<\/strong><\/h1>\n<p>dp[i] := span of prices[i]<\/p>\n<p>j = i &#8211; 1<br>\nwhile j &gt;= 0 and prices[i] &gt;= prices[j]: j -= dp[j]<br>\ndp[i] = i &#8211; j<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua, 144 ms\nclass StockSpanner {\npublic:\n  StockSpanner() {}\n\n  int next(int price) {\n    if (prices_.empty() || price &lt; prices_.back()) {\n      dp_.push_back(1);      \n    } else {\n      int j = prices_.size() - 1;\n      while (j &gt;= 0 &amp;&amp; price &gt;= prices_[j]) {\n        j -= dp_[j];\n      }\n      dp_.push_back(prices_.size() - j);\n    }    \n    prices_.push_back(price);    \n    return dp_.back();\n  }\nprivate:\n  vector&lt;int&gt; dp_;\n  vector&lt;int&gt; prices_;  \n};<\/pre>\n<\/div><\/div>\n<h1><strong>Solution 3: Monotonic Stack<\/strong><\/h1>\n<p>Maintain a monotonic stack whose element are pairs of &lt;price, span&gt;, sorted by price from high to low.<\/p>\n<p>When a new price comes in<\/p>\n<ol>\n<li>If it&#8217;s less than top price, add a new pair (price, 1) to the stack, return 1<\/li>\n<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>\n<\/ol>\n<p>e.g. prices: 10, 6, 5, 4, 3, 7<\/p>\n<p>after 3, the stack looks [(10,1), (6,1), (5,1), (4,1), (3, 1)],<\/p>\n<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>\n<p>Time complexity: O(1) amortized, each element will be pushed on to stack once, and pop at most once.<\/p>\n<p>Space complexity: O(n), in the worst case, the prices is in descending order.<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\nclass StockSpanner {\npublic:\n  StockSpanner() {}\n\n  int next(int price) {\n    int span = 1;\n    while (!s_.empty() &amp;&amp; price &gt;= s_.top().first) {\n      span += s_.top().second;  \n      s_.pop();\n    }\n    s_.emplace(price, span);\n    return span;\n  }\nprivate:\n  stack&lt;pair&lt;int, int&gt;&gt; s_; \/\/ {price, span}, ordered by price DESC.\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true\">\/\/ Author: Huahua\nclass StockSpanner {\n  private Stack&lt;Integer&gt; prices;\n  private Stack&lt;Integer&gt; spans;\n  public StockSpanner() {\n    prices = new Stack&lt;&gt;();\n    spans = new Stack&lt;&gt;();\n  }\n\n  public int next(int price) {\n    int span = 1;\n    while (!prices.empty() &amp;&amp; price &gt;= prices.peek()) {\n      span += spans.pop();\n      prices.pop();\n    }\n    prices.push(price);\n    spans.push(span);\n    return span;\n  }\n}<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Python3<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true\"># Author: Huahua\nclass StockSpanner:\n  def __init__(self):\n    self.s = list()\n\n  def next(self, price):\n    span = 1\n    while self.s and price &gt;= self.s[-1][0]:\n      span += self.s[-1][1]\n      self.s.pop()\n    self.s.append((price, span))\n    return span<\/pre>\n<\/div><\/div>\n<h1><strong>Related Problems<\/strong><\/h1>\n<ul>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/simulation\/leetcode-735-asteroid-collision\/\">\u82b1\u82b1\u9171 LeetCode 735. Asteroid Collision<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/heap\/leetcode-239-sliding-window-maximum\/\">\u82b1\u82b1\u9171 LeetCode 239. Sliding Window Maximum<\/a><\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>Problem Write a class&nbsp;StockSpanner&nbsp;which collects daily price quotes for some stock, and returns the&nbsp;span&nbsp;of that stock&#8217;s price for the current day. The span of the&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46,407],"tags":[18,217,389,180],"class_list":["post-3969","post","type-post","status-publish","format-standard","hentry","category-dynamic-programming","category-stack","tag-dp","tag-hard","tag-monotonic","tag-stack","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3969","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=3969"}],"version-history":[{"count":11,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3969\/revisions"}],"predecessor-version":[{"id":6186,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3969\/revisions\/6186"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=3969"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=3969"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=3969"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}