Say you had an array for which the ith element was 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.
This is very intuitive, the direct difference between the highest value on the line, the start of the tle once, because the use of O (n^2)
method, and later found O (n) to be able.
The first code:
classSolution { Public:intMaxprofit ( vector<int>&prices) {if(prices.size () = =0|| Prices.size () = =1)return 0;intAns =0; for(intI=1; I<prices.size (); i++) { for(intj=i+1; J<prices.size (); j + +)if(Prices[j]-prices[i] > ans) ans = prices[j]-prices[i]; }returnAns }};
Correct:
classSolution { Public:intMaxprofit ( vector<int>&prices) {if(prices.size () = =0|| Prices.size () = =1)return 0;intans = int_min;intLow = prices[0]; for(intI=1; I<prices.size (); i++) {if(Low > Prices[i]) low = prices[i];Else if(Prices[j]-low >ans) ans = prices[j] – low; }returnAns }};
[Leetcode] best time to Buy and Sell Stock