LeetCode——Best Time to Buy and Sell Stock IV
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; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。







