class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length < 2 || k == 0) return 0;
int[] dp = new int[k*2];
for(int i = 0; i < k;i++){
dp[i*2] = -prices[0];
}
for(int j = 0;j < prices.length;j++){
int price = prices[j];
for(int i = 0;i < 2 * k;i++){
if(i == 0) dp[i] = Math.max(dp[i],-price);
else dp[i] = Math.max(dp[i - 1] - price,dp[i]);
i++;
dp[i] = Math.max(dp[i - 1] + price,dp[i]);
}
}
return dp[k * 2 - 1];
}
}
06-21
782