123. 买卖股票的最佳时机 III(进阶版本【188. 买卖股票的最佳时机 IV】)
题目:
思路:
【1】利用了第一次与第二次结合同时买入和卖出的想法,获取这种操作下能赚取的最大值。
代码展示:
【1】123. 买卖股票的最佳时机 III
//时间1 ms 击败 100% //内存54.5 MB 击败 69.24% class Solution { public int maxProfit(int[] prices) { int n = prices.length; int buy1 = -prices[0], sell1 = 0; int buy2 = -prices[0], sell2 = 0; for (int i = 1; i < n; ++i) { buy1 = Math.max(buy1, -prices[i]); sell1 = Math.max(sell1, buy1 + prices[i]); buy2 = Math.max(buy2, sell1 - prices[i]); sell2 = Math.max(sell2, buy2 + prices[i]); } return sell2; } }
【2】188. 买卖股票的最佳时机 IV
//时间1 ms 击败 99.90% //内存39.3 MB 击败 90.2% class Solution { public int maxProfit(int k, int[] prices) { int n = prices.length; // 因为存在一买一卖,所以最大买卖次数便是数组的一半 k = Math.min(k, n / 2); if (k == 0) return 0; int[] buy = new int[k], sell = new int[k]; Arrays.fill(buy, -prices[0]); for (int i = 0; i < n; ++i) { buy[0] = Math.max(buy[0], -prices[i]); sell[0] = Math.max(sell[0], buy[0] + prices[i]); for (int j = 1 ; j < k; j++){ buy[j] = Math.max(buy[j], sell[j-1] - prices[i]); sell[j] = Math.max(sell[j], buy[j] + prices[i]); } } return sell[k-1]; } }