给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考:
(1)https://blog.csdn.net/wangquan1992/article/details/107084445
(2)https://www.cnblogs.com/labuladong/p/12320374.html
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = size(prices);
if(len < 2)
{
return 0;
}
vector<int> hasStock(len);
vector<int> nonStock(len);
hasStock[0] = -prices[0];
nonStock[0] = 0;
hasStock[1] = max(hasStock[0], nonStock[0]-prices[1]);
nonStock[1] = max(prices[1]-prices[0],0);
for(int i = 2; i < len; i++)
{
hasStock[i] = max(hasStock[i-1], nonStock[i-2]- prices[i]);
nonStock[i] = max(nonStock[i-1], hasStock[i-1] + prices[i]);
}
return nonStock[len-1];
}
};