Best Time to Buy and Sell Stock IV
可以买卖k次,DP来解决,
t[i][j] = Math.max(t[i][j - 1], prices[j] + buy) 即得出在prices[j]卖出时的最大利润;
buy= Math.max(buy, t[i - 1][j - 1] - prices[j]) 则得出在prices[j]买进后剩下的钱,留待下次卖出.
当k大于等于len/2时,问题转化为可以买卖任意次的Best Time to Buy and Sell Stock II ,不然会很不efficient,会超时。
当k=2时,则转化为买卖两次的Best Time to Buy and Sell Stock III 。
参考链接: 链接一
而链接二 中的local,global变量的方法与 Maximum Subarray 一样,但是不好理解。
public class Solution { public int maxProfit(int k, int[] prices) { int len = prices.length; if (k > len / 2) return quickSolve(prices); int[][] dp = new int[k + 1][len]; for(int i = 1; i <= k; i++) { int buy = -prices[0]; for(int j = 1; j < len; j++) { dp[i][j] = Math.max(dp[i][j - 1], prices[j] + buy); buy = Math.max(buy, dp[i - 1][j - 1] - prices[j]); } } return dp[k][len - 1]; } private int quickSolve(int[] prices) { int len = prices.length, profit = 0; for (int i = 1; i < len; i++) // as long as there is a price gap, we gain a profit. if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; } }

浙公网安备 33010602011771号