java solution
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if(n == 1) return 0;
if(k >= n/2) {
return maxProfitUnlimited(prices);
}
//创建dp数组
int[][] dp = new int[k + 1][n];
for(int i = 1; i <= k; i++) {
int maxDiff = -prices[0]; //最开始dp[0][j] = 0, 所以 maxDiff 初始值为 -prices[0]
for(int j = 1; j < n; j++) {
dp[i][j] = Math.max(dp[i][j - 1], prices[j] + maxDiff);
maxDiff = Math.max(maxDiff, dp[i - 1][j] - prices[j]);
//dp[i][j] = Math.max(dp[i][j - 1], \sigma 1-m (prices[j] - prices[m] + dp[i - 1][m]))
//本来dp[i][j]是这个状态转移方程,为了优化计算,我们把prices[j]提出来,剩余部分定义为maxDiff
}
}
return dp[k][n - 1];
}
private int maxProfitUnlimited(int[] prices) {
int profit = 0;
for(int i = 1; i < prices.length; i++) {
if(prices[i] > prices[i - 1]) {
profit