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).
Idea: Dynamic programming. Since at most 2 transactions are allowed, we can think it as at any time slot t , there is a buy/sell transaction pair on t's left side and a buy/sell pair on t's right. By assuming each time slot as the middle point, get an array of the maximal profits. Then the maximum number of the sum of the left profit and the right profit will be the result.
Assuming the middle point is x, the left maximal profit leftMax(x) =Math.max(leftMax[x-1], prices[x]- the valley price appeared before). The right maximal profit rightMax(x)=Math.max(rightMax[x+1], the peak price appeared before - prices[x]).
Time: O(n) Space: O(n)
Code:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length<2)
return 0;
int[] left=new int[prices.length];
int[] right=new int[prices.length];
for(int i=1,valley=prices[0];i<prices.length;i++)
{
left[i]=Math.max(left[i-1],prices[i]-valley);
valley=Math.min(valley,prices[i]);
}
for(int j=prices.length-2,peak=prices[prices.length-1];j>=0;j--)
{
right[j]=Math.max(right[j+1],peak-prices[j]);
peak=Math.max(peak,prices[j]);
}
int result=0;
for(int i=0;i<prices.length;i++)
result=Math.max(result,left[i]+right[i]);
return result;
}
}
No comments:
Post a Comment