解题思路
动态规划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]);
}
}