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.
The main idea: to an array, the first element of an array is the share price of the first day of a stock, design an algorithm to find the maximum profit.
Problem-solving ideas: Obviously buy before, sell in, this problem n^2 approach is not AC, the way to do it, F represents the Profit function, then F[i]=price[i]-price[min], where min<i, if price[i]<price[min ], then update min=i.
Talk is cheap>>
Public intMaxprofit (int[] prices) { if(Prices = =NULL|| Prices.length <= 1) { return0; } intMin_pos = 0; intProfit =Integer.min_value; for(inti = 0; i < prices.length; i++) { intTmp_pro = Prices[i]-Prices[min_pos]; if(Prices[i] <Prices[min_pos]) {Min_pos=i; } Profit=Math.max (Profit,tmp_pro); } returnprofit; }
best time to Buy and Sell Stock--leetcode