Description
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
1.You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
2.After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Solution 1(C++)
class Solution{
public:
int maxProfit(vector<int>& prices){
if(prices.empty()) return 0;
vector<int> buy(prices.size(), 0);
vector<int> sell(prices.size(), 0);
buy[0] = -prices[0];
for(int i=1; i<prices.size(); i++){
buy[i] = max(buy[i-1], sell[i-2] - prices[i]);
sell[i] = max(sell[i-1], buy[i-1] + prices[i]);
}
return sell.back();
}
};
后续更新
其他类似题目可参考:
- LeetCode-121. Best Time to Buy and Sell Stock
- LeetCode-122. Best Time to Buy and Sell Stock II
- LeetCode-714. Best Time to Buy and Sell Stock with Transaction Fee
- -
算法分析
买股票的系列动态规划问题。两个状态相互依靠,注意这里有冷却时间。有空把这几个题都看一看。
程序分析
略。