714. Best Time to Buy and Sell Stock with Transaction Fee
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int[] buy = new int[n]; // buy[n]表示在第n天 持有股票的最大利润
int[] sell = new int[n]; // sell[n]表示在第n天 没有持有股票的最大利润
buy[0] = -prices[0];
sell[0] = 0;
for(int i = 1; i < n; i++) {
// 持有股票有可能是前一天就持有的,有可能前一天没有持有当天买入的
buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i]);
// 不持有股票有可能前一天就不持有,有可能当天卖出后不持有,当天卖出收取transaction fee
sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i] - fee);
}
return sell[n - 1]; // 交易完毕手里没有股票
}
}
309. Best Time to Buy and Sell Stock with Cooldown
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int len = prices.length;
// 定义dp数组:dp[i]表示第i天的最大利润,dp[i][0]表示当天不持有股票,dp[i][1]表示当天持有股票
int[][] dp = new int[len][2];
dp[0][0] = 0;
dp[0][1] = 0 - prices[0]; // 第0天持有买入利润为负的减去prices[0]
for (int i = 1; i < len; i++) {
//当天不持有股票有两种情况:当天卖出去的, 前一天就没有,两种情况选择最大值
dp[i][0] = Math.max(dp[i - 1][1] + prices[i], dp[i - 1][0]);
//当天持有股票有两种情况:当天买入的(因为存在冷冻期,当天买入说明至少前两天就没有,
//不然前一天就没有的话当天肯定不能买入),前一天就有的, 两种情况选择最大值
dp[i][1] = Math.max(dp[i - 1][1], ((i - 2) >= 0 ? dp[i - 2][0] : 0) - prices[i]);
}
// 最后两种情况选择最大值
return Math.max(dp[len - 1][1], dp[len - 1][0]);
}
}
123. Best Time to Buy and Sell Stock III
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
// 定义左右两个数组分别记录从左到右和从右到左的最大profit
int[] left = new int[n], right = new int[n];
// for循环记录从左到右的profit
int min = prices[0];
for (int i = 1; i < n; i++) {
left[i] = Math.max(left[i - 1], prices[i] - min);
min = Math.min(min, prices[i]);
}
// for循环记录从右到左的profit
int max = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
right[i] = Math.max(right[i + 1], max - prices[i]);
max = Math.max(max, prices[i]);
}
// for循环计算最大profit
int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, left[i] + right[i]);
}
return ans;
}
}
122. Best Time to Buy and Sell Stock II
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1; i < prices.length; i++) {
res += Math.max((prices[i] - prices[i - 1]), 0);
}
return res;
}
}
121. Best Time to Buy and Sell Stock
class Solution {
public int maxProfit(int[] prices) {
int max1 = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++) {
max1 = Math.max(max1, prices[i] - min);
min = Math.min(min, prices[i]);
}
return max1;
}
}