309.最佳买卖股票时机含冷冻期
解法:代码随想录
题目:- LeetCode
这道题我觉得只用三个状态更好理解,设立一个冷却期冷却期的值就是卖后的值,而持有期基于冷静期来计算。
class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length][2];
dp[0][0] = -prices[0]; //持有
dp[0][1] = 0; //不持有
System.out.print(dp[0][0] + " ");
System.out.print(dp[0][1] + " ");
for (int i = 1; i < prices.length; ++i) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
System.out.print(dp[i][0] + " ");
System.out.print(dp[i][1] + " ");
}
return dp[prices.length - 1][1];
}
}
714.买卖股票的最佳时机含手续费
解法:代码随想录
题目:- LeetCode
这道题就是2的变体加个fee就行了
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int free = 0, hold = -prices[0];
for (int i = 1; i < n; i++) {
int tmp = hold;
hold = Math.max(hold, free - prices[i]);
free = Math.max(free, tmp + prices[i] - fee);
}
return free;
}
}