Best Time to Buy and Sell Stock IV

Say you have an array for which the ith element is the price of a given stock on day i.

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

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Solution:

  1. public class Solution {
  2. public int maxProfit(int k, int[] prices) {
  3. int n = prices.length;
  4. if (k >= n) {
  5. return solveMaxProfit(prices);
  6. }
  7. // The local array tracks maximum profit of j transactions & the last transaction is on ith day.
  8. // The global array tracks the maximum profit of j transactions until ith day.
  9. int[][] local = new int[n][k + 1];
  10. int[][] global = new int[n][k + 1];
  11. for (int i = 1; i < n; i++) {
  12. int diff = prices[i] - prices[i - 1];
  13. for (int j = 1; j <= k; j++) {
  14. local[i][j] = Math.max(
  15. global[i - 1][j - 1] + Math.max(diff, 0),
  16. local[i - 1][j] + diff
  17. );
  18. global[i][j] = Math.max(global[i - 1][j], local[i][j]);
  19. }
  20. }
  21. return global[n - 1][k];
  22. }
  23. private int solveMaxProfit(int[] prices) {
  24. int profit = 0;
  25. for (int i = 1; i < prices.length; i++) {
  26. // as long as there is a price gap, we gain a profit.
  27. if (prices[i] > prices[i - 1]) {
  28. profit += prices[i] - prices[i - 1];
  29. }
  30. }
  31. return profit;
  32. }
  33. }