188. Best Time to Buy and Sell Stock IV
class Solution { public int maxProfit(int k, int[] prices) { if(k>=prices.length/2) { int maxProfit=0; for(int i=1;i<prices.length;i++) maxProfit+=prices[i]>prices[i-1]?prices[i]-prices[i-1]:0; return maxProfit; } int[] buys=new int[k]; Arrays.fill(buys, Integer.MIN_VALUE); int[] sells=new int[k]; for(int p: prices) { for(int i=k-1;i>=0;i--) { sells[i]=Math.max(sells[i], buys[i]+p); if(i==0) buys[i]=Math.max(buys[i], -p); else buys[i]=Math.max(buys[i], sells[i-1]-p); } } return k>0?sells[k-1]:0; } }