题目

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

  1. Input: k = 2, prices = [2,4,1]
  2. Output: 2
  3. Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

  1. Input: k = 2, prices = [3,2,6,5,0,3]
  2. Output: 7
  3. Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

Constraints:

  • 0 <= k <= 10^9
  • 0 <= prices.length <= 10^4
  • 0 <= prices[i] <= 1000

题意

股票买卖问题之四,允许最多k次交易(k次买入k次卖出)。

思路

解法在 0309. Best Time to Buy and Sell Stock with Cooldown (M) 的基础上增加一个k次交易的限制。

0188. Best Time to Buy and Sell Stock IV (H) - 图1表示在第i天仍持有股票,且最多已进行了j次交易。
0188. Best Time to Buy and Sell Stock IV (H) - 图2表示在第i天未持有任何股票,且最多已进行了j次交易。

可以得到如下递推关系:

0188. Best Time to Buy and Sell Stock IV (H) - 图3

边界条件是:0188. Best Time to Buy and Sell Stock IV (H) - 图4

需要注意的是,case可能会使坏给一个巨大的k值,导致超时。这里的一个技巧是,当k大于数组长度一半时时,问题就等同于可以进行不限次数的交易,可以直接用 0122. Best Time to Buy and Sell Stock II (E) 中的一次遍历方法解决。


代码实现

Java

  1. class Solution {
  2. public int maxProfit(int k, int[] prices) {
  3. if (prices.length == 0) {
  4. return 0;
  5. }
  6. if (k > prices.length / 2) {
  7. return maxProfit(prices);
  8. }
  9. int[][] hold = new int[prices.length][k + 1];
  10. int[][] sold = new int[prices.length][k + 1];
  11. for (int i = 0; i < prices.length; i++) {
  12. for (int j = 1; j <= k; j++) {
  13. if (i == 0) {
  14. hold[i][j] = -prices[i];
  15. } else {
  16. hold[i][j] = Math.max(hold[i - 1][j], sold[i - 1][j - 1] - prices[i]);
  17. sold[i][j] = Math.max(hold[i - 1][j] + prices[i], sold[i - 1][j]);
  18. }
  19. }
  20. }
  21. return sold[prices.length - 1][k];
  22. }
  23. private int maxProfit(int[] prices) {
  24. int profit = 0;
  25. for (int i = 1; i < prices.length; i++) {
  26. if (prices[i] > prices[i - 1]) {
  27. profit += prices[i] - prices[i - 1];
  28. }
  29. }
  30. return profit;
  31. }
  32. }