-
Notifications
You must be signed in to change notification settings - Fork 2
/
188.best-time-to-buy-and-sell-stock-iv.java
48 lines (41 loc) · 1.24 KB
/
188.best-time-to-buy-and-sell-stock-iv.java
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
/*
* @lc app=leetcode id=188 lang=java
*
* [188] Best Time to Buy and Sell Stock IV
*/
// @lc code=start
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (n == 0) {
return 0;
}
if (k > n / 2) {
return maxProfit_caseII(prices);
}
int[][][] dp = new int[n][k + 1][2];
for (int i = 0; i < prices.length; i++) {
for (int j = k; j >= 1; j--) {
if (i - 1 == -1) {
dp[i][j][0] = 0;
dp[i][j][1] = -prices[i];
continue;
}
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]);
}
}
return dp[n - 1][k][0];
}
public int maxProfit_caseII(int[] prices) {
int dp_i_0 = 0;
int dp_i_1 = Integer.MIN_VALUE;
for (int i = 0; i < prices.length; i++) {
int temp = dp_i_0;
dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1, temp - prices[i]);
}
return dp_i_0;
}
}
// @lc code=end