[LeetCode] 188. 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).

Thought process:
Dynamic programming.
  1. Sub-problem: the max profit given prices[0, a] where a < prices.length and b trades, where b < k.
  2. Function: Use a variable to keep track of current asset.
    1. f[i][j] = max(f[i][j - 1] (not selling), asset + prices[j] (selling)).
    2. asset = max(asset (not buying), f[i - 1][j - 1] - prices[j] (buying)).
  3. Initialization: default 2-D array.
  4. Answer: f[k][prices.length].

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

Time complexity: O(kn).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 410. Split Array Largest Sum