给定一个整数数组prices,其中第 prices[i] 表示第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入: prices = [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
> 动态规划
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 1) return 0;
// 其实是三种状态
int hold = INT_MIN; //持有股票时的最大利润
int free = 0; //不冻结 不持有股票时的最大利润
int cd = 0; //处于冷冻期时的最大利润
//转移关系为:
// hold[i] = free[i-1] - prices[i] 、hold[i-1]
// free[i] = free[i-1] 、cd[i-1]
// cd[i] = hold[i-1] + prices[i]
for(const auto &p:prices){
int pre_cd = cd;
cd = hold + p;
hold = std::max(free - p,hold);
free = std::max(free,pre_cd);
}
return std::max(cd,free);
}
};