class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n == 1) {
return 0;
} else if (n == 2) {
return Math.max(prices[1] - prices[0], 0);
}
int result = 0;
int buy1 = Math.max(-prices[0], -prices[1]);
int notBuy1 = Math.max(0, buy1 + prices[1]);
int buy2 = notBuy1 - prices[1];
int notBuy2 = Math.max(0, buy2 + prices[1]);
for (int i = 2; i < prices.length; i++) {
buy1 = Math.max(buy1, -prices[i]);
notBuy1 = Math.max(notBuy1, buy1 + prices[i]);
buy2 = Math.max(buy2, notBuy1 - prices[i]);
notBuy2 = Math.max(notBuy2, buy2 + prices[i]);
}
result = Math.max(result, buy1);
result = Math.max(result, notBuy1);
result = Math.max(result, buy2);
result = Math.max(result, notBuy2);
return result;
}
}
123. 买卖股票的最佳时机 III
最新推荐文章于 2024-08-14 11:57:07 发布