思路: 早就知道这题要用dp做的我依旧像往常一样没有做出来,甚至一开始傻傻的以为用一维dp数组就可以解决。well(手动微笑)。之后开始了看答案之旅,well,看了三小时,终于算是懂了。其实如果只是要get idea的话,那可能半小时我就看懂了。只是有一个小的细节我一直在纠结,并且调试代码。我发现好像大家的答案都是默认可以在同一天,先卖了股票,再买。可是按照题目的意思应该是不行的吧。所以我尝试在他们的代码上修改,但是发现修改成题意之后,答案是错的。后来索性我就不纠结了,就默认可以同一天先卖再买吧。具体的思路可以看这个链接:链接。下面我直接上代码了:
public class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (k >= n/2) {
int maxProfit = 0;
for (int i = 1; i < n; i++) {
int diff = prices[i] - prices[i-1];
if (diff > 0) {
maxProfit += diff;
}
}
return maxProfit;
}
// Each element dp[i][j] means the max profit of at most i transactions until day j
int[][] dp = new int[k+1][n];
for (int i = 1; i <= k; i++) {
for (int j = 1; j < n; j++) {
int max = Integer.MIN_VALUE;
for(int jj = 0; jj < j; jj++){
max= Math.max(max, dp[i - 1][jj] - prices[jj]);
dp[i][j] = Math.max(dp[i][j - 1], prices[j] + max);
}
}
}
return dp[k][n - 1];
}
}
总结: 无