LeetCode-123 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.
思路1:
从n个点中任选一个点,将整个输入分为两个部分,求两个部分的最大收益,即为整体的最大收益。
如果只是简单的遍历每个点,会计算超时,因此需要过滤掉一些不可能划分的点。
为了使总的收益最大,分割点不应该在上升区间;而每个下降区间的任意两点对结果的影响是相同的,所以我们的划分点只要选择极大值点或者极小值点即可。
我的代码中选择极大值点。
代码如下:
public int maxProfit(List<Integer> prices) { if(prices == null || prices.size() < 2) return 0; int max = 0; int top = prices.get(0); for(int i=1; i<prices.size(); ) { while(i<prices.size() && prices.get(i) >= prices.get(i-1)) i++; int maxLeft = maxOneProfit(prices, 0, i-1); int maxRight = maxOneProfit(prices, i, prices.size()-1); if(maxLeft+maxRight > max) max = maxLeft+maxRight; while(i<prices.size() && prices.get(i) <= prices.get(i-1)) i++; } return max; } public int maxOneProfit(List<Integer> prices, int start, int end) { if(prices == null || end-start < 1) return 0; int min = prices.get(start); int maxProfit = 0; for(int i=start+1; i<=end; i++) { if(prices.get(i) > min) { maxProfit = (prices.get(i)-min > maxProfit ? prices.get(i)-min : maxProfit); } else { min = prices.get(i); } } return maxProfit; }
思路2:
1、 题目要求最多交易两次,如果只交易一次,问题就是“Best Time to Buy and Sell Stock”;
如果必须交易两次,设第一次交易在第i个交易日卖出,则问题退化成求0到i交易日的最大收益和i+1到最后一个交易日的最大收益。
2、 因此,从第1个交易日起,求到第i个交易日的最大收益,其中1<i<=A.length,得到数组maxLeft;
从最后一个交易开始,求第i个交易日到最后一个交易日的最大收益,其中1<=i<A.length,得到数组maxRight;
3. 从maxLeft和maxRight即可求出最大收益
代码如下:
1 public int maxProfit(int[] prices) { 2 if(prices == null || prices.length < 2) return 0; 3 int[] lToR = new int[prices.length]; 4 int[] rToL = new int[prices.length]; 5 6 int min = prices[0]; 7 for(int i=1; i<prices.length; i++) { 8 if(prices[i] > min) { 9 lToR[i] = prices[i]-min > lToR[i-1] ? prices[i]-min : lToR[i-1]; 10 } else { 11 lToR[i] = lToR[i-1]; 12 min = prices[i]; 13 } 14 } 15 16 int max = prices[prices.length-1]; 17 for(int i=prices.length-2; i>=0; i--) { 18 if(prices[i] < max) { 19 rToL[i] = max-prices[i] > rToL[i+1] ? max-prices[i] : rToL[i+1]; 20 } else { 21 rToL[i] = rToL[i+1]; 22 max = prices[i]; 23 } 24 } 25 26 int maxProfit = lToR[prices.length-1]; 27 for(int i=0; i<prices.length-1; i++) { 28 maxProfit = lToR[i]+rToL[i+1] > maxProfit ? lToR[i]+rToL[i+1] : maxProfit; 29 } 30 return maxProfit; 31 }
posted on 2015-03-16 00:41 linxiong1991 阅读(115) 评论(0) 编辑 收藏 举报