Update Leetcode to solve Java answers on a regular basis.
Choose from the pick one approach.
Test instructions to allow only one sale, the given array is the price of the item of the day, ask the maximum benefit is how much.
Obviously the best way to get the most benefit is to iterate through the array, and in the process of traversal, the price of each day is read, and it is compared with the minimum value obtained by the preceding traversal, which is the maximum benefit to sell a single time on that day. It is stored and compared with later values in subsequent operations, playable a larger value, and the final result is the maximum possible result for a single transaction.
The code is as follows:
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 if(Prices.length = = 0)4 return0;5 intMinprice = Prices[0], max = 0;6 for(inti = 1; i < prices.length; i++){7 if(Prices[i]-minprice >max)8max = Prices[i]-Minprice;9 if(Prices[i] <minprice)TenMinprice =Prices[i]; One } A returnMax; - } -}
Python has been recently known, and occasionally the Python version is issued.
1 classsolution (object):2 defMaxprofit (Self, prices):3 """4 : Type Prices:list[int]5 : Rtype:int6 """7 ifLen (prices) = =0:8 return09Max =0TenMinprice =Prices[0] One A forPriceinchPrices: - ifMax < price-Minprice: -max = Price-Minprice the ifPrice <Minprice: -Minprice = Price - - returnMax
121. Best time to Buy and Sell Stock