|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=188 lang=java |
| 3 | + * |
| 4 | + * [188] Best Time to Buy and Sell Stock IV |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +class Solution { |
| 9 | + /* |
| 10 | +如果k >= prices.length / 2, 则视为可以无限次交易 |
| 11 | +我们定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为: |
| 12 | +local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff) |
| 13 | +global[i][j] = max(local[i][j], global[i - 1][j]) |
| 14 | +time: O(kn) |
| 15 | +space: O(k) |
| 16 | + */ |
| 17 | + public int maxProfit(int k, int[] prices) { |
| 18 | + if (prices == null || prices.length == 0) return 0; |
| 19 | + if (k >= prices.length / 2) return unlimitedProfit(prices); |
| 20 | + int[] local = new int[k + 1]; |
| 21 | + int[] global = new int[k + 1]; |
| 22 | + for (int i = 0; i < prices.length - 1; ++i) { |
| 23 | + int diff = prices[i + 1] - prices[i]; |
| 24 | + for (int j = k; j >= 1; --j) { |
| 25 | + local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); |
| 26 | + global[j] = Math.max(global[j], local[j]); |
| 27 | + } |
| 28 | + } |
| 29 | + return global[k]; |
| 30 | + } |
| 31 | + |
| 32 | + private int unlimitedProfit(int[] prices) { |
| 33 | + int res = 0; |
| 34 | + for (int i = 0; i < prices.length - 1; ++i) { |
| 35 | + if (prices[i + 1] - prices[i] > 0) { |
| 36 | + res += prices[i + 1] - prices[i]; |
| 37 | + } |
| 38 | + } |
| 39 | + return res; |
| 40 | + } |
| 41 | +} |
| 42 | +// @lc code=end |
| 43 | + |
0 commit comments