Description:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
动态规划,有递推式:参考:http://blog.csdn.net/feliciafay/article/details/45128771
local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),
global[i][j]=max(local[i][j],global[i-1][j])
public class Solution { public int maxProfit(int k, int[] prices) { int len = prices.length; if(len < 2) { return 0; } if(k > len) { return bigProfit(prices); } int[] local = new int[k+1]; int[] global = new int[k+1]; Arrays.fill(local, 0); Arrays.fill(global, 0); for(int i=0; i<len-1; i++) { int diff = prices[i+1] - prices[i]; for(int j=k; j>=1; j--) { local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff); global[j] = Math.max(global[j], local[j]); } } return global[k]; } public int bigProfit(int[] prices) { int res = 0; for(int i=0; i<prices.length-1; i++) { if(prices[i] < prices[i+1]) { res += prices[i+1] - prices[i]; } } return res; } }