From 6bc2b03cf80c5ba859deb06709e0c33a9366dfbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sun, 2 Sep 2018 17:44:57 +0800 Subject: [PATCH] Create 122. Best Time to Buy and Sell Stock II.md --- 122. Best Time to Buy and Sell Stock II.md | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 122. Best Time to Buy and Sell Stock II.md diff --git a/122. Best Time to Buy and Sell Stock II.md b/122. Best Time to Buy and Sell Stock II.md new file mode 100644 index 0000000..0f678b5 --- /dev/null +++ b/122. Best Time to Buy and Sell Stock II.md @@ -0,0 +1,42 @@ +# [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) +# 思路 +## 比较好想的思路 +如果分别知道了前0到前i天的最大利润dp[0...i],那么前i+1天的最大利润就为: +max(dp[j] + max(prices[i+1] - prices[k])), 其中k属于j~i+1 +以上思路时间复杂度为O(n^2), 空间复杂度为O(n) +## 改进 +运用贪心的思想:只要有利润(即prices[i] > prices[i-1])就可以买入卖出, 即不错过任何利润。 +此时时间复杂度O(n), 空间复杂度为O(1) + +# C++ +改进前: +``` +class Solution { +public: + int maxProfit(vector& prices) { + if(prices.size() == 0) return 0; + int dp[prices.size()] = {0}; + int min_price; + for(int i = 1; i < prices.size(); i++){ + min_price = prices[i]; + for(int j = i-1; j >= 0; j--){ + if(min_price > prices[j]) min_price = prices[j]; + if(dp[j] + prices[i] - min_price > dp[i]) dp[i] = dp[j] + prices[i] - min_price; + } + } + return dp[prices.size() - 1]; + } +}; +``` +改进后: +``` +class Solution { +public: + int maxProfit(vector& prices) { + int max_profit = 0; + for(int i = 1; i < prices.size(); i++) + if(prices[i] > prices[i-1]) max_profit += (prices[i] - prices[i-1]); + return max_profit; + } +}; +```