My LeetCode Diary - Day50 Dynamic Programming
123. Best Time to Buy and Sell Stock III
Link
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int max_k = 2;
int[][][] dp = new int [n][max_k+1][2];
for (int i = 0; i<n;i++) {
for(int k = max_k; k >= 1; k--) {
if (i-1 == -1) {
dp[i][k][0] = 0;
dp[i][k][1] = -prices[i];
continue;
}
if (i-2 == -1) {
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1]+prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1], -prices[i]);
continue;
}
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1]+prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1], dp[i-1][k-1][0]-prices[i]);
}
}
return dp[n-1][max_k][0];
}
}
188. Best Time to Buy and Sell Stock IV
Link
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 0) return 0;
int len = prices.length;
int[][][] dp = new int[len][k + 1][2];
for (int i = 0; i <= k; i++) {
dp[0][i][1] = -prices[0];
}
for (int i = 1; i < len; i++) {
for (int j = 1; j <= k; j++) {
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[len - 1][k][0];
}
}