LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee
阿新 • • 發佈:2018-11-07
題解型別
這裡有一篇極盡完美的足以秒殺所有 stock buy&sell 型別的題解,寫的非常完善。
給出我覺得重要的點:
T[ i, k, b ] 表示到i位為止交易k次情況下 是否(b=0 or 1)持有股票時獲得最大收益
- 邊界條件
T[-1][k][0] = 0, T[-1][k][1] = -Infinity
T[i][0][0] = 0, T[i][0][1] = -Infinity
- 迭代式
// 賣出 or keep
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
// 買入 or keep。 特別記 買入消耗一次交易次數
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])// here k-1
Code
int maxProfit(vector<int>& prices, int fee) {
int t_i0,t_i1;
t_i0=0;
t_i1=-99999;
for(int p:prices){
int old_ti0 = t_i0;
t_i0=max(t_i0,t_i1+p-fee);
t_i1= max(t_i1,old_ti0-p);
}
return t_i0;
}