https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/?tab=Description
题目是最多两次,但是下面的解法非常好,也能够覆盖仅仅一次的情况。
https://discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1/2
代码很简短,思路也非常好:
public class Solution { public int maxProfit(int[] prices) { int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE; int release1 = 0, release2 = 0; for(int i:prices){ // Assume we only have 0 money at first release2 = Math.max(release2, hold2+i); // The maximum if we've just sold 2nd stock so far. hold2 = Math.max(hold2, release1-i); // The maximum if we've just buy 2nd stock so far. release1 = Math.max(release1, hold1+i); // The maximum if we've just sold 1nd stock so far. hold1 = Math.max(hold1, -i); // The maximum if we've just buy 1st stock so far. } return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1. } }
但是上面对于最多N次这种更加通用的形式,就不太好用了。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/?tab=Description
上面对于最多买n次类型的题目,要用到DP才行。
解法看这里:
https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java
其实含义也很明确:
tmpMax是当前时间状态持股之后的最大收益(很可能是负的)
t[i][j]是记录的实际收益。
public int maxProfit(int k, int[] prices) { int len = prices.length; if (k >= len / 2) return quickSolve(prices); int[][] t = new int[k + 1][len]; for (int i = 1; i <= k; i++) { int tmpMax = -prices[0]; for (int j = 1; j < len; j++) { t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); tmpMax = Math.max(tmpMax, t[i - 1][j - 1] - prices[j]); } } return t[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; }