121 power button topic: the best time to buy and sell stocks, python implementation, study notes

Title: Given an array, which i-th element is a given stock i-day prices.
If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.
Be careful not to sell the stock before buying stocks.
Example:
Input: [7,1,5,3,6,4]
Output: 5
to buy the next day to 1 yuan, on day 5 to sell price 6.
Note that profits can not be 7-1 = 6, 7 is because selling price, selling price can not be before the purchase price.

Analysis: The
maximum profit = max (maximum price the previous, current price - the minimum purchase price before)
need to initialize the maximum profit and minimum prices, the need to find the maximum price, the initial value should be set to a smaller number, due to the profit of a minimum of 0 Therefore it is initialized to 0; for a minimum price is concerned, the need to find the smallest price, so it needs to be initialized to a larger number.
code show as below:

在这里插入代码片
def maxProfit(self,prices:List[int]):
    max_profit = 0
    min_price = float("inf")
    for price in prices:
    	max_profit = max(max_profit,price-min_price)
    	min_price = min(price,min_price)
    return max_profit
Released three original articles · won praise 2 · views 38

Guess you like

Origin blog.csdn.net/Mr_LHS/article/details/104747399