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).
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 if(prices.length<=1) {4 return0;5 }6 7 int[] left =New int[prices.length];8 int[] right =New int[prices.length];9 intMin = prices[0];Ten for(inti = 1; i < prices.length; i++) { OneLeft[i] = left[i-1] > prices[i]-min? LEFT[I-1]: prices[i]-min; Amin = min < prices[i]?Min:prices[i]; - } - the intmax = Prices[prices.length-1]; - for(inti = prices.length-2; I >= 0; i--) { -Right[i] = right[i + 1] > Max-prices[i]? Right[i + 1]: max-Prices[i]; -max = max > Prices[i]?Max:prices[i]; + } - intsum =Integer.min_value; + for(inti = 0; i < left.length; i++) { Asum = SUM > left[i] + right[i]? Sum:left[i] +Right[i]; at } - returnsum; - } -}
Leetcode best time to Buy and Sell Stock III