贪心算法
class Solution {
public int maxProfit(int[] prices, int fee) {
if(prices.length < 2) return 0;
int profit = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++){
if(prices[i] < min){
min = prices[i];//更新最低价的股票
} else {
if(prices[i] - fee > min){//可以卖出
profit += prices[i] - fee - min;
min = prices[i] - fee;
}
}
}
return profit;
}
}
动态规划
dp[i][j]表示在第i天在未持有股票(0)和持有股票(1)的情况下的最大利润。
在当天交易后未持有股票可能有两种情况:1、在当天卖出了股票;2、当天没有交易,既没买也没卖。所以dp[i][0]的状态转移方程是:dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + price[i] - fee)
在当天交易后持有股票可能有两种情况:1、在当天买入了股票;2、当天没有买,但是之前买的股票没卖.所以dp[i][0]的状态转移方程是:dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - price[i])
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
if(n < 2) return 0;
int[][] dp = new int[n][2];
//初始的边界条件
dp[0][1] = -prices[0];
dp[0][0] = 0;
for(int i = 1; i < n; i++){
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}