LeetCode Best Time to Buy and keep Stock
Best Time to Buy and Stock for LeetCode solving
Original question
Given the daily stock price, if only one round of trading is allowed, that is, the maximum profit can be obtained by buying and selling the stock once.
Note:
None
Example:
Input: prices = [2, 4, 6, 1, 3, 8, 3]
Output: 7 (buy when the price is 1 and sell when the price is 8)
Solutions
In the previous traversal of the series, we used the lowest price we have ever seen as the purchase price and calculated the benefits we have sold at the current price. During the whole traversal process, the biggest benefit we have ever seen is what we want.
AC Source Code
Class Solution (object): def maxProfit (self, prices): "": type prices: List [int]: rtype: int "if len (prices) <2: return 0 min_price = prices [0] max_profit = 0 for price in prices: if price <min_price: min_price = price if price-min_price> max_profit: max_profit = price-min_price return max_profitif _ name _ = "_ main _": assert Solution (). maxProfit ([2, 4, 6, 1, 3, 8, 3]) = 7