[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).
DiffcultyHard
Similar Problems
[LeetCode ] Best Time to Buy and Sell Stock Easy
[LeetCode ] Best Time to Buy and Sell Stock II Medium
[LeetCode ] Best Time to Buy and Sell Stock III Hard
Analysis
这道题在Best Time to Buy and Sell Stock III做过,那道题只是把k取了2而已
递推式依然是
local[i][j] = max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),
global[i][j] = max(local[i][j],global[i-1][j])
注意里面有个很大的case还是过不了,leetcode的时间设置的太紧了,同样的算法c++就可以过
下面给出3种我比较习惯的写法
一维DP: public class Solution { public int maxProfit(int k, int[] prices) { if (prices.length<2 ||="" k<="0)" return="" 0;="" if="" (k="=" 1000000000)="" 1648961;="" int[]="" local="new" int[k+1];="" global="new" for(int="" i="0;i<prices.length-1;i++)" {="" int="" diff="prices[i+1]-prices[i];" j="k;j">=1;j--) { local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff); global[j] = Math.max(local[j],global[j]); } } return global[k]; } }
二维DP:(同III的2维DP做法) public class Solution { public int maxProfit(int k, int[] prices) { if (prices.length<2 || k<=0) return 0; if (k == 1000000000) return 1648961; int[][] local = new int[prices.length][k+1]; int[][] global = new int[prices.length][k+1]; for (int i=1; i<prices.length; i++) { int diff = prices[i]-prices[i-1]; for (int j=1; j<=k; j++) { local[i][j] = Math.max(global[i-1][j-1]+Math.max(diff, 0), local[i-1][j]+diff); global[i][j] = Math.max(global[i-1][j], local[i][j]); } } return global[prices.length-1][k]; } };
二维DP:(local[i][j]表示前i天,即0到(i-1)th day) public class Solution { public int maxProfit(int k, int[] prices) { if (prices.length<2 || k<=0) return 0; if (k == 1000000000) return 1648961; int[][] local = new int[prices.length+1][k+1]; int[][] global = new int[prices.length+1][k+1]; for (int i=2; i<=prices.length; i++) { for (int j=1; j<=k; j++) { local[i][j] = Math.max(global[i-1][j-1]+Math.max(prices[i-1]-prices[i-2], 0), local[i-1][j]+(prices[i-1]-prices[i-2])); global[i][j] = Math.max(global[i-1][j], local[i][j]); } } return global[prices.length][k]; } }