Say you have an array for whichITh element is the price of a given stock on dayI.
Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).
Problem: DP
Scan the array from the past to the next, and use lefttoright [I] to record (0, I) to get the maximum profit;
Scan the array from the back and forth, and use righttoleft [I] to record (I, n-1) the maximum profit;
The final maximum profit is max (lefttoright [I] + righttoleft [I]).
For example, if prices = {1, 2, 3, 2, 5, 7 },
Lefttoright = {0, 1, 2, 4, 6}
Righttoleft = {6, 5, 5, 2, 0}
The final maximum profit is 2 + 5 = 7. Indicates that ~ 2 (or 0 ~ 3) the profit is 2 in this range, and 2 ~ 5 (or 3 ~ 5) profit is 5 in this range, and the final profit is 7.
The Code is as follows:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices == null || prices.length == 0) 4 return 0; 5 6 int[] LeftToRight = new int[prices.length]; 7 int[] RightToLeft = new int[prices.length]; 8 9 int minimal = prices[0];10 LeftToRight[0] = 0;11 for(int i = 1;i < prices.length;i++){12 minimal = Math.min(minimal, prices[i]);13 LeftToRight[i] = Math.max(LeftToRight[i-1], prices[i]-minimal);14 }15 16 int profit = 0;17 //From Right to left18 RightToLeft[prices.length-1] = 0;19 int maximal = prices[prices.length-1];20 for(int i = prices.length-2;i >= 0;i--){21 maximal = Math.max(prices[i], maximal);22 RightToLeft[i]= Math.max(RightToLeft[i+1], maximal-prices[i]);23 profit = Math.max(profit, LeftToRight[i] + RightToLeft[i] );24 }25 26 return Math.max(profit, LeftToRight[0]+RightToLeft[0]);27 }28 }