Leetcode 188. Best Time to Buy and Sell Stock IV
很久很久没有刷到这么好的题目了,很经典的DP题目,动态规划简而言之,就是要学会分情况讨论。
public class Solution {
public static void main(String[] args){
Solution s = new Solution();
int[] k = {6,1,3,2,4,7};
int r = s.maxProfit(2, k);
System.out.println(r);
}
public int maxProfit(int k, int[] prices) {
int len = prices.length;
if(k>=len){
int res = 0;
for(int i=1;i<len;i++){
if(prices[i]>prices[i-1]){
res += prices[i] - prices[i-1];
}
}
return res;
}
int[][] local = new int[len][k+1];
int[][] global = new int[len][k+1];
for(int i=1;i<len;i++){
int diff = prices[i] - prices[i-1];
int res = prices[i] > prices[i-1] ? diff:0;
for(int j=1;j<=k;j++){
local[i][j] = global[i-1][j-1]+res>local[i-1][j]+diff?global[i-1][j-1]+res:local[i-1][j]+diff;
global[i][j] = global[i-1][j]>local[i][j]?global[i-1][j]:local[i][j];
}
}
return global[len-1][k];
}
}