題目鏈接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
題目標簽:Array,DP
此題與123. Best Time to Buy and Sell Stock III 相比,交易數(shù)量由2個上升至K個,基本思路還是一樣,只是現(xiàn)在要同時更新k個buy,k個sell。
Java代碼:
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
if(len==0 || k==0){
return 0;
}
if (k>= len/2){
return quickSolve(prices);
}
int[][] statue = new int[k][len];
// initialize statue[0]
int buy = -prices[0];
for (int i=1; i<len; i++){
statue[0][i] = Math.max(statue[0][i-1], prices[i] + buy);
buy = Math.max(buy, -prices[i]);
}
// fullfill statue
for (int i=1; i<k; i++){
buy = -prices[0];
for (int j=1; j<len; j++){
statue[i][j] = Math.max(statue[i][j-1], prices[j] + buy);
buy = Math.max(buy, statue[i-1][j-1]-prices[j]);
}
}
return statue[k-1][len-1];
}
private int quickSolve(int[] prices){
int len = prices.length;
int res = 0;
for(int i=1; i<len; i++){
int p1 = prices[i-1];
int p2 = prices[i];
if(p2>p1){
res += p2-p1;
}
}
return res;
}
}
Edge case:
k = 0
prices = []
k>=prices.length/2