Question
Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Solution
This problem can is solved by "divide and conquer". We can use Left[i] array to track maximum profit for transactions before I (including i), and Right[i + 1] to track Maximu M profit for Transcations after I.
Prices:1 4 5 7 6 3 2 9left = [0, 3, 4, 6, 6, 6, 6, 8]right= [8, 7, 7, 7, 7, 7, 7, 0]
Time complexity O (n), Space cost O (n).
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 if(Prices = =NULL|| Prices.length < 2)4 return0;5 intLength = prices.length, Min = prices[0], max = prices[length-1], Tmpprofit = 0;6 int[] Leftprofits =New int[length];7Leftprofits[0] = 0;8 int[] Rightprofits =New int[length];9Rightprofits[length-1] = 0;Ten //Calculat left side profits One for(inti = 1; i < length; i++) { A if(Prices[i] >min) -Tmpprofit = Math.max (Tmpprofit, Prices[i]-min); - Else theMin =Prices[i]; -Leftprofits[i] =Tmpprofit; - } - //Calculate right side profits +Tmpprofit = 0; - for(intj = length-2; J >= 0; j--) { + if(Prices[j] <max) ATmpprofit = Math.max (Tmpprofit, Max-prices[j]); at Else -Max =Prices[j]; -RIGHTPROFITS[J] =Tmpprofit; - } - //Sum up - intresult =Integer.min_value; in for(inti = 0; i < length-1; i++) -result = Math.max (result, leftprofits[i] + rightprofits[i + 1]); toresult = Math.max (result, leftprofits[length-1]); + returnresult; - } the}
best time to Buy and Sell Stock III solution