Say you have an array for which the i-th 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).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
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.
classSolution {publicintmaxProfit(int price[],int i,int n,int K,int dp[][][],int ongoing) {if (i == n)return0;if (K ==0) { dp[i][K][ongoing] =0;return0; }if (dp[i][K][ongoing] !=-1)return dp[i][K][ongoing];int ans =maxProfit(price, i +1, n, K, dp, ongoing);if (ongoing ==1) {int option =maxProfit(price, i +1, n, K -1, dp,0)+ price[i]; ans =Math.max(ans, option); } else {int option =maxProfit(price, i +1, n, K, dp,1)- price[i]; ans =Math.max(ans, option); } dp[i][K][ongoing] = ans;return ans; }publicintmaxProfit(int k,int[] prices) {int n =prices.length;if (n <=1)return0;// if k >= n/2, then you can make maximum number of transactions.// Then this question is similar to infinite transactionsif (k >= n /2) {int T_ik0 =0, T_ik1 =Integer.MIN_VALUE;for (int price : prices) {int T_ik0_old = T_ik0;// If we want 0 stocks in our hand at end of ith day// Either take ans from 0 stock i-1th day// Or take ans from 1 stock i-1th day and sell it T_ik0 =Math.max(T_ik0, T_ik1 + price);// If we want 1 stock in our hand at end of ith day// Either take ans from 1 stock i-1th day// Or take ans from 0 stock i-1th day and but 1 stock at ith day T_ik1 =Math.max(T_ik1, T_ik0_old - price); }return T_ik0; }int dp[][][] =newint[n +1][k +1][2];for (int i =0; i <= n; i++) {for (int j =0; j <= k; j++) { dp[i][j][0] =-1; dp[i][j][1] =-1; } }returnmaxProfit(prices,0, n, k, dp,0); }}