Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
First, the problem is converted to a mathematical language: array a[n], and for any i < J < N, Max (A[j]-a[i]) is calculated.
The results can be obtained using O (n^2) method.
The following dynamic planning methods are analyzed:
For input prices[n], if known profit[i-1],
1) when Prices[i] <= prices[i-1], obviously, profit[i] = profit[i-1]
2) when prices[i] > Prices[i-1], remember bottom = min (prices[0, 1, ..., i]), if
Prices[i]-bottom > Profit[i-1] There are
Profit[i] = prices[i]- Bottom
Otherwise, profit[i] = profit[i-1]
1 intMaxprofit (vector<int> &prices)2 {3 intn =prices.size (), bottom, max_profit;4 if(N <=1)5 return 0;6 int*profit =New int[n];7profit[0] =0;8Bottom = prices[0];9 for(inti =1; I < n; i++)Ten { OneBottom =min (bottom, prices[i]); A if(Prices[i] > Prices[i-1] && prices[i]-bottom > Profit[i-1]) - { -Profit[i] = prices[i]-Bottom; the } - Else - { -Profit[i] = profit[i-1]; + } - } +Max_profit = Profit[n-1]; A Delete profit; at returnMax_profit; -}
Leetcode. best time to Buy and Sell Stock