Extended from Best Time to Buy and Sell Stock III.

```
public int maxProfit(int k, int[] prices) {
if(prices.length ==0){
return 0;
}
if(k>=prices.length/2){
int maxProfit = 0;
for(int i=1; i<prices.length; i++){
maxProfit += Math.max(0, prices[i]-prices[i-1]);
}
return maxProfit;
}
int[] buy = new int[k+1]; //profit after buying at k-th transaction
int[] sell = new int[k+1]; //profit at k-th transaction
Arrays.fill(buy, Integer.MIN_VALUE);
Arrays.fill(sell, 0);
for(int price : prices){
for(int i = 1; i<=k;i++){
buy[i] = Math.max(buy[i], sell[i-1]- price);
sell[i] = Math.max(sell[i], buy[i] + price);
}
}
return sell[k];
}
```