[leetcode] Best Time to Buy and Sell Stock III
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 two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
思路:因为两次交易不能重叠,所以需要扫描两边分别求两段的最大值。dp[i]代表prices[0..i]的最大值,dpRev[i]代表prices[i..n]的最大值。然后求出max(dp[i]+dpRev[i]) 0<=i<=n-1
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int n = prices.length; int res = 0; int[] dp = new int[n]; int[] dpRev = new int[n]; dp[0] = 0; dpRev[n - 1] = 0; int curMin = prices[0]; for (int i = 1; i < n; i++) { dp[i] = Math.max(dp[i - 1], prices[i] - curMin); if (prices[i] < curMin) curMin = prices[i]; } int curMax = prices[n - 1]; for (int i = n - 2; i >= 0; i--) { dpRev[i] = Math.max(dpRev[i + 1], curMax - prices[i]); if (prices[i] > curMax) curMax = prices[i]; res = Math.max(res, dp[i] + dpRev[i]); } return res; } }
第二遍记录:
注意dp 和 dpDev代表的具体含义。
第三遍记录:
注意当天卖了之后可以再买
注意写的时候小心,prices,dp,dpRev不要写错了。
参考: