动态规划
class Solution { public int maxProfit(int[] prices, int fee) { // 0 买入股票 // 1 不持有股票 int size = prices.length; if(size < 2 ) return 0; int dp[][] = new int [size][2]; dp[0][0] = -prices[0]; for(int i = 1; i < size; 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] - fee); } return Math.max(dp[size - 1][0],dp[size - 1][1]); }}
滚动数组
class Solution {
public int maxProfit(int[] prices, int fee) {
// 0 买入股票
// 1 不持有股票
int size = prices.length;
if(size < 2 ) return 0;
int dp[] = new int[2];
dp[0] = -prices[0];
for(int i = 1; i < size; i++ ) {
dp[0] = Math.max(dp[0], dp[1] - prices[i]);
dp[1] = Math.max(dp[1],dp[0] + prices[i] - fee);
}
return Math.max(dp[0],dp[1]);
}
}