Create 122. Best Time to Buy and Sell Stock II.md

This commit is contained in:
唐树森 2018-09-02 17:44:57 +08:00 committed by GitHub
parent 1d33ccea72
commit 6bc2b03cf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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<int>& 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<int>& 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;
}
};
```