解題思路
動態規劃dp[i][j]表示第i天持股(j=1)不持股(j=0)的最大收益
初始狀態,第0天持股的最大收益dp[0][1] = -price[0] - fee = -(第0天股票的費用+賣出去的手續費)
因爲,你持股不賣一定比持股賣掉收益大
初始狀態,第0天不持股的最大收益dp[0][0] = 0,狀態轉移方程就很好想了,見代碼
class Solution {
public int maxProfit(int[] prices, int fee) {
// dp[i][j]最大收益
// i表示第i天
// j = 0 表示不持股,j = 1表示持股
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0] - fee;
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][0] - prices[i] - fee, dp[i-1][1]);
}
return Math.max(dp[prices.length-1][0],dp[prices.length-1][1]);
}
}