{"id":1319,"date":"2017-12-22T17:32:19","date_gmt":"2017-12-23T01:32:19","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1319"},"modified":"2018-01-08T09:00:44","modified_gmt":"2018-01-08T17:00:44","slug":"leetcode-121-best-time-to-buy-and-sell-stock","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/dynamic-programming\/leetcode-121-best-time-to-buy-and-sell-stock\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 121. Best Time to Buy and Sell Stock"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 121. Best Time to Buy and Sell Stock - \u5237\u9898\u627e\u5de5\u4f5c EP140\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/8pVhUpF1INw?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><\/p>\n<p>\u9898\u76ee\u5927\u610f: \u7ed9\u4f60\u4e00\u53ea\u80a1\u7968\u6bcf\u5929\u7684\u4ef7\u683c\uff0c\u5982\u679c\u53ea\u80fd\u505a\u4e00\u6b21\u4ea4\u6613\uff08\u4e00\u6b21\u4e70\u8fdb\u4e00\u6b21\u5356\u51fa\uff09\u95ee\u4f60\u6700\u591a\u80fd\u8d5a\u591a\u5c11\u94b1\u3002<\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Say you have an array for which the\u00a0<i>i<\/i><sup>th<\/sup>\u00a0element is the price of a given stock on day\u00a0<i>i<\/i>.<\/p>\n<p>If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: [7, 1, 5, 3, 6, 4]\r\nOutput: 5\r\n\r\nmax. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"\">Input: [7, 6, 4, 3, 1]\r\nOutput: 0\r\n\r\nIn this case, no transaction is done, i.e. max profit = 0.<\/pre>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1561\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/121-ep140-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/121-ep140-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/121-ep140-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/12\/121-ep140-1-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>DP<\/p>\n<p><strong>Solution 1:<\/strong><\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 6 ms\r\nclass Solution {\r\npublic:\r\n    int maxProfit(vector&lt;int&gt;&amp; prices) {\r\n        const int n = prices.size();\r\n        if (n &lt; 1) return 0;\r\n        vector&lt;int&gt; min_prices(n);\r\n        vector&lt;int&gt; max_profit(n);\r\n        min_prices[0] = prices[0];\r\n        max_profit[0] = 0;\r\n        for (int i = 1; i &lt; n; ++i) {\r\n            min_prices[i] = min(min_prices[i - 1], \r\n                                prices[i]);\r\n            \r\n            max_profit[i] = max(max_profit[i - 1], \r\n                                prices[i] - min_prices[i - 1]);\r\n        }\r\n        return max_profit[n - 1];\r\n    }\r\n};<\/pre>\n<p>C++ \/ reduce to maximum subarray<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 6 ms\r\nclass Solution {\r\npublic:\r\n    int maxProfit(vector&lt;int&gt;&amp; prices) {\r\n        int n = prices.size();\r\n        if (n &lt; 2) return 0;\r\n        vector&lt;int&gt; gains(n - 1, 0);\r\n        for (int i = 1; i &lt; n; ++i)\r\n            gains[i - 1] = prices[i] - prices[i - 1];\r\n        return max(0, maxSubArray(gains));\r\n    }\r\nprivate:\r\n    \/\/ From LC 53. Maximum Subarray\r\n    int maxSubArray(vector&lt;int&gt;&amp; nums) {\r\n        vector&lt;int&gt; f(nums.size());\r\n        f[0] = nums[0];\r\n        \r\n        for (int i = 1; i &lt; nums.size(); ++i)\r\n            f[i] = max(f[i - 1] + nums[i], nums[i]);\r\n        \r\n        return *std::max_element(f.begin(), f.end());\r\n    }\r\n};<\/pre>\n<p><strong>Related Problems:<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/dynamic-programming\/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown\/\">\u82b1\u82b1\u9171 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\u9898\u76ee\u5927\u610f: \u7ed9\u4f60\u4e00\u53ea\u80a1\u7968\u6bcf\u5929\u7684\u4ef7\u683c\uff0c\u5982\u679c\u53ea\u80fd\u505a\u4e00\u6b21\u4ea4\u6613\uff08\u4e00\u6b21\u4e70\u8fdb\u4e00\u6b21\u5356\u51fa\uff09\u95ee\u4f60\u6700\u591a\u80fd\u8d5a\u591a\u5c11\u94b1\u3002 Problem: Say you have an array for which the\u00a0ith\u00a0element is the price of a given stock on day\u00a0i. If you were only permitted&#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,163],"tags":[192,182,206],"class_list":["post-1319","post","type-post","status-publish","format-standard","hentry","category-dynamic-programming","category-easy","tag-max-subarray","tag-reduction","tag-stock","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1319","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=1319"}],"version-history":[{"count":5,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1319\/revisions"}],"predecessor-version":[{"id":1562,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1319\/revisions\/1562"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1319"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1319"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1319"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}