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).
Using left[i] and right[J] respectively for the first and second sell income, where left[I] represents the I element before the buy sell stock can make the most money, right[i] represents i element after buy sell stock can earn the most money,
The following is a concrete implementation PS: can buy and sell the same day
public class Solution {public int maxprofit (int[] prices) { if (prices.length<2) return 0; int []left =new int[prices.length]; int []right = new Int[prices.length]; int minval = prices[0]; for (int i=1;i<prices.length;i++) { minval = math.min (Minval, prices[i]); Left[i] = Math.max (left[i-1], prices[i]-minval); } int maxval = prices[prices.length-1]; for (int i=prices.length-2;i>=0;i--) { maxval = Math.max (Maxval, prices[i]); Right[i] = Math.max (right[i+1], maxval-prices[i]); } int res = Left[0]+right[0]; for (int i=1;i<prices.length;i++) { res = Math.max (res, left[i]+right[i]); } return res; }}
[Leetcode]best time to Buy and Sell Stock III