给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
示例 1:
输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
注意:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
思路: 好久没做动态规划了,脑子生锈了。具体就是必须分析清楚题目里隐含的状态。
1.先定义状态,dp[i][j] i就是代表[0.....i]天,j为0代表不持股,1代表持股
2.再转移方程 ,不持股可以由持股和不持股选择而来,持股可以由持股和不持股选择而来。(动态规划需要选择!!!其实就是max,min之类的)
3.初始化
class Solution {
public int maxProfit(int[] prices, int fee) {
if (prices == null ||prices.length < 2) return 0;
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++) {
for (int j = 0;j < 2;j++) {
if (j == 0) {
dp[i][j] = Math.max(dp[i-1][0],dp[i-1][1] + prices[i]);
} else {
dp[i][j] = Math.max(dp[i-1][0] - prices[i] - fee,dp[i-1][1]);
}
}
}
return dp[prices.length-1][0];
}
}