只能进行 k 次的股票交易
188. Best Time to Buy and Sell Stock IV (Hard)
题目描述:
只能进行K次股票交易,求能获得的最大利润
思路分析:
和只能进行两次股票交易的思路相同,将两次换成k次
代码:
class Solution {
public int maxProfit(int k,int []prices){
if(prices==null||prices.length==0)
return 0;
int []local=new int [k+1];
int []global=new int [k+1];
for(int i=0;i<prices.length-1;i++){
int diff=prices[i+1]-prices[i];
for(int j=k;j>=1;j--){
local[j]=Math.max(global[j-1]+(diff>0?diff:0),local[j]+diff);
global[j]=Math.max(local[j],global[j]);
}
}
return global[k];
}
}