Test instructions: Given a sequence, the element I represents the price of this stock for the first day, asking how much money can be earned at the best time to buy and sell? Buy only once, and only 1 shares, assuming unlimited cost.
Idea: To find a low-priced time to buy, at the highest price when the sale of profits will be the biggest. But time is not a conflict, for example buy tomorrow, sell today. Therefore, for today's price, we should find the lowest price of the stock before today, buy, sell today.
In fact, for one element in the sequence a[k], find another element a[e], the position satisfies e<k, the result makes a[k]-a[e] maximum.
With dynamic planning, the current minimum value is updated with an element from left sweep, and the current element is used to reduce the minimum value. We'll know the result after sweep.
classSolution { Public: intMaxprofit (vector<int>&prices) { intSmall=2147483647, ans=0; for(intI=0; I<prices.size (); i++) {Small=min (small, prices[i]);//find the minimum value before IAns=max (prices[i]-small, ans); } returnans; }};
AC Code
Leetcode best time to buy and Sell stock trading stock (DP)