private static int maxProfit(int k,int []prices){
if(prices==null || prices.length==0)
return 0;
if(prices.length<k){
return maxProfit2(prices);
}
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];
}
private static int maxProfit2(int[] prices){
int maxMoney=0;
int count=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i]<=prices[i+1]){
count++;
}else{
maxMoney+=prices[i]-prices[i-count];
count=0;
}
}
if(count>0){
maxMoney+=prices[prices.length-1]-prices[prices.length-1-count];
}
return maxMoney;
};