Only every time I look at this picture of the C + + does not have a white learning AH ~ ~ ~ usually with the time of the different Miss Eclipse, all kinds of nostalgia java~~~
This is the biggest profit, originally I think is to find the minimum and maximum, the difference is not the maximum profit, and then think, the minimum may be after the maximum value, can not be said to buy back in number 3rd to sell the stock and then think, record the minimum value before the day, and then record the maximum value after that day, Such a calculation will be able to calculate the maximum profit in a certain period of time, and then more than a few periods of profit, can calculate the ultimate maximum profit.
Class Solution { //maxval[i] and Minval[i] represent the maximum value after I and the minimum before I, and then traverse one side to calculate the maximum profit public: int Maxprofit (vector<int > &prices) { if (Prices.empty ()) return 0; const int size = Prices.size (); int maxval[size], minval[size]; int Maxprofit (int_min); Minval[0] = prices[0]; MAXVAL[SIZE-1] = prices[size-1]; for (int i = 1; i < size; I + +) { Minval[i] = min (minval[i-1], prices[i]); } for (int i = size-2; I >= 0; I-) { maxval[i] = max (maxval[i+1], prices[i]); } for (int i = 0; i < size; I + +) { Maxprofit = max (Maxprofit, Maxval[i]-minval[i]); } return maxprofit;} ;
Leetcode--best time to Buy and Sell Stock