1.題目
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).
給定一個數組,每個元素分別代表每天的股票價格,要求最多可進行兩次交易,求得獲取的最大利潤和。注意:買入必須在賣出之前,同一時間只能進行一次交易。
2.分析
該題目如果不要求時間複雜度,則可直接通過遍歷一邊數組,找出所有連續增加的值得最大和最小值的差值,然後在這些差值中找出最大的兩個然後求和即爲我們的求解結果。但是這種做法時間複雜度爲O(n2),顯然有很大的優化空間。
由題意分析得出滿足動態規劃的要求。採用空間換時間方法,以第i天爲分界線,計算第i天之前進行一次交易的最大收益preProfit[i],和第i天之後進行一次交易的最大收益postProfit[i],最後遍歷一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之後進行一次的最大收益求法同Best Time to Buy and Sell Stock I。
code:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2){
return 0;
}
int len=prices.length;
int preProfit[]=new int[len];
int postProfit[]=new int[len];
int curMin=prices[0];
preProfit[0]=0;
for(int i=1;i<len;i++){
curMin=Math.min(curMin,prices[i]);
preProfit[i]=Math.max(preProfit[i-1],prices[i]-curMin);
}
postProfit[len-1]=0;
int curMax=prices[len-1];
for(int i=len-2;i>=0;i--){
curMax=Math.max(curMax,prices[i]);
postProfit[i]=Math.max(postProfit[i+1],curMax-prices[i]);
}
int maxProfit=0;
for(int i=0;i<len;i++){
maxProfit=Math.max(maxProfit,preProfit[i]+postProfit[i]);
}
return maxProfit;
}
}