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).
将数组分成两段,分别计算出每段的最大利润,然后相加与之交易一次的最大利润作比较,最后输出最大值。
具体:
1.计算交易一次的最大利润max:从左到右遍历数组,计算每个i位置的最大利润同时将利润值保存在数组maxLeft
2.从右到左遍历数组:将数组分成两段:1~i,i~length-1,1~i段的最大利润值maxLeft[i],计算i~length-1的最大利润
同时保存在数组maxRight中,计算maxRight[i]与maxLeft[i]的值,若该值比max大则将其赋值给max。
public class Solution {
public int maxProfit(int[] prices) {
int max=0;
int length=prices.length;
if(length<=1){
return max;
}
int [] maxLeft=new int[length];
int lowest=prices[0];
maxLeft[0]=0;
for(int i=1;i<length;i++){
if(lowest<prices[i]){
int profit=prices[i]-lowest;
if(profit>maxLeft[i-1]){
maxLeft[i]=profit;
}else{
maxLeft[i]=maxLeft[i-1];
}
}else{
lowest=prices[i];
maxLeft[i]=maxLeft[i-1];
}
}
max=maxLeft[length-1];
int [] maxRight=new int[length];
int high=prices[length-1];
maxRight[length-1]=0;
for(int i=length-2;i>=0;i--){
if(prices[i]<high){
int profit=high-prices[i];
if(profit>maxRight[i+1]){
maxRight[i]=profit;
}else{
maxRight[i]=maxRight[i+1];
}
}else{
high=prices[i];
maxRight[i]=maxRight[i+1];
}
int sum=maxLeft[i]+maxRight[i];
if(sum>max){
max=sum;
}
}
return max;
}
}