标签:
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、 题目要求最多交易两次,如果只交易一次,问题就是“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即可求出最大收益
代码如下:
public int maxProfit(int[] prices) { if(prices.length < 2) return 0; int[] maxLeft = new int[prices.length]; int lastIn = 0;//表示最低买入股价在第lastIn天 for(int i=1; i<prices.length;i++) { if(maxLeft[i-1] == 0) { if(prices[i] > prices[i-1]) { maxLeft[i] = prices[i] - prices[i-1]; lastIn = i-1; } } else { if(prices[i] > prices[lastIn]) { if(prices[i] - prices[lastIn] > maxLeft[i-1]) { maxLeft[i] = prices[i] - prices[lastIn]; } else { maxLeft[i] = maxLeft[i-1]; } } else if(prices[i] < prices[lastIn]) { maxLeft[i] = maxLeft[i-1]; lastIn = i; } else { maxLeft[i] = maxLeft[i-1]; } } } int[] maxRight = new int[prices.length]; int lastOut = prices.length;//表示最高卖出股价在第lastOut天 for(int i=prices.length-2; i>=0; i--) { if(maxRight[i+1] == 0) { if(prices[i] < prices[i+1]) { maxRight[i] = prices[i+1] - prices[i]; lastOut = i+1; } }else { if(prices[i] < prices[lastOut]) { if(prices[lastOut] - prices[i] > maxRight[i+1]) { maxRight[i] = prices[lastOut] - prices[i]; } else { maxRight[i] = maxRight[i+1]; } } else if(prices[i] > prices[lastOut]){ maxRight[i] = maxRight[i+1]; lastOut = i; } else { maxRight[i] = maxRight[i+1]; } } } int max = 0; for(int i=1; i<prices.length-2; i++) { if(maxLeft[i] + maxRight[i+1] > max) max = maxLeft[i] + maxRight[i+1]; } if(max < maxLeft[prices.length-1]) { max = maxLeft[prices.length-1]; } return max; }
LeetCode-123 Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4340892.html