[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).
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.
- Sub-problem: the max profit given prices[0, a] where a < prices.length and b trades, where b < k.
- Function: Use a variable to keep track of current asset.
- f[i][j] = max(f[i][j - 1] (not selling), asset + prices[j] (selling)).
- asset = max(asset (not buying), f[i - 1][j - 1] - prices[j] (buying)).
- Initialization: default 2-D array.
- 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
Post a Comment