原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
本题是Best Time to Buy and Sell Stock III的general情况。
但这里要注意若是k很大已经超过了prices.length的时候,若是按照DP的方法做会浪费时间以及空间。
此时可以直接参照Best Time to Buy and Sell Stock II的做法。
AC Java:
public class Solution {
public int maxProfit(int k, int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
if(k>=prices.length){
int res = 0;
for(int i = 1; i < prices.length; i++){
res += Math.max(0, prices[i]-prices[i-1]);
}
return res;
}
int[] local = new int[k+1];
int[] global = new int[k+1];
for(int i = 1; i<prices.length; i++){
int diff = prices[i] - prices[i-1];
for(int j = k; j>=1; j--){
local[j] = Math.max(global[j-1] + Math.max(diff,0), local[j] + diff);
global[j] = Math.max(global[j], local[j]);
}
}
return global[k];
}
}