leetcode 股票买卖(动态规划)
这位大佬四种题型总结的很好:link
一共只有三种状态:买、卖、冷冻
b u y [ i ] buy[i] buy[i] 表示第i天之前最后一次行为是buy时,最大的收益
s e l l [ i ] sell[i] sell[i]表示第i天之前最后一次行为是sell时,最大的收益
r e s t [ i ] rest[i] rest[i]表示第i天之前最后一次行为是冷冻rest时,最大的收益
b u y [ i ] = m a x ( b u y [ i − 1 ] , r e s t [ i − 1 ] − p r i c e s [ i ] ) buy[i]=max(buy[i−1],rest[i−1]−prices[i]) buy[i]=max(buy[i−1],rest[i−1]−prices[i]),max(第i天冷冻, 第i天是卖出)
s e l l [ i ] = m a x ( s e l l [ i − 1 ] , b u y [ i − 1 ] + p r i c e s [ i ] ) sell[i]=max(sell[i−1],buy[i−1]+prices[i]) sell[i]=max(sell[i−1],buy[i−1]+prices[i]),max(第i天冷冻,第i天是买入)
r e s t [ i ] = m a x ( r e s t [ i − 1 ] , b u y [ i − 1 ] , s e l l [ i − 1 ] ) rest[i]=max(rest[i−1],buy[i−1],sell[i−1]) rest[i]=max(rest[i−1],buy[i−1],sell[i−1])
class Solution {
public:
int maxProfit(vector<int>& prices) {
// 有冷冻期 不限制买卖次数 但是卖完股票后有一天的冷冻期才能再接着买
int n = prices.size();
if(n<=1) return 0;
vector<int> buy(n, INT_MIN), sell(n, INT_MIN), rest(n, INT_MIN);
buy[0] = -prices[0];
sell[0] = 0;
rest[0] = 0;
for(int i=1; i<n; i++){
buy[i] = max(buy[i-1], rest[i-1]-prices[i]);
sell[i] = max(sell[i-1], buy[i-1]+prices[i]);
rest[i] = max(rest[i-1], max(buy[i-1], sell[i-1]));
}
return max(buy[n-1], max(sell[n-1], rest[n-1]));
}
};
PS: 我现在还不能想出来,动态规划的转移方程很重要啊,我还不熟练,要好好练