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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { public int maxProfit(int k, int[] prices) { int n = prices.length; if (n <= 0 || k <= 0) { return 0; }
if (2*k > n) { int res = 0; for (int i = 1; i < n; i++) { res += Math.max(0, prices[i] - prices[i - 1]); } return res; }
int[][][] dp = new int[n][k+1][2];
for (int i = 0; i < n; i++) { for (int j = 0; j <= k; j++) { dp[i][j][0] = -1000000000; dp[i][j][1] = -1000000000; } }
dp[0][0][0] = 0; dp[0][1][1] = -prices[0];
for (int i = 1; i < n; i++) { for (int j = 0; j <=k ; j++) { dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
if (j > 0) { dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]); } } }
int res = 0; for (int j = 0; j <= k; j++) { res = Math.max(res, dp[n-1][j][0]); }
return res; } }
|