Day 42 动态规划 Part09
188. 买卖股票的最佳时机 IV
做完上一道题后再看就简单许多了。股票问题的重点就在于两点:
- 找到所有的状态
- 状态如何转移
对于本题,一共包含2*k
种状态(第1,2...k次持有,第1,2...k次卖出)。状态间如何转移呢?见下图
class Solution {
public int maxProfit(int k, int[] prices) {
int[] states = new int[2*k];
Arrays.fill(states, Integer.MIN_VALUE);
for(int i = 0; i < prices.length; i++){
for(int j = 0; j < k; j++){
states[2*j] = Math.max(states[2*j],
2*j == 0 ? -prices[i] : states[2*j-1] - prices[i]);
states[2*j+1] = Math.max(states[2*j+1],
states[2*j] + prices[i]);
}
}
return states[2*k-1];
}
}
309. 买卖股票的最佳时机含冷冻期
难度还是挺大,尽管最后写出来了,但感觉写完自己也不是很确定。也是两部,确定所有的状态,再确定状态如何转移。
- 包含三种状态,分别为 非冷冻(未持有) 冷冻(未持有) 持有
- 状态转移图
- 确定好这两点再去实现代码就不会乱套了
class Solution {
public int maxProfit(int[] prices) {
int[] stat = new int[3];
// 三种状态
//分别为 非冷冻(未持有) 冷冻(未持有) 持有
stat[0] = 0; stat[1] = 0; stat[2] = -1 * prices[0];
for(int i = 1; i < prices.length; i++){
stat[0] = Math.max(stat[0], stat[1]); //当天非冷冻 前一天非冷冻|前一天冷冻
stat[1] = stat[2] + prices[i-1]; //当天冷冻 一定是前一天持有
stat[2] = Math.max(stat[2], stat[0]-prices[i]); //当天持有 前一天持有|今天非冷冻
}
return Math.max(Math.max(stat[0], stat[1]), stat[2] + prices[prices.length-1]);
//最后一天三种状态,非持有两种, 持有需要卖出再比较
}
}
714. 买卖股票的最佳时机含手续费
class Solution {
public int maxProfit(int[] prices, int fee) {
int stat1 = -1 * prices[0] - fee;
int stat2 = 0;
for(int i = 1; i < prices.length; i++){
stat1 = Math.max(stat1, stat2 - fee - prices[i]);
stat2 = Math.max(stat2, stat1 + prices[i]);
}
return stat2;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步