Array
121. Best Time to Buy and Sell Stock
Say you have an array for which the element is the price of a given stock on day
.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
即在最便宜的时候买入,在最贵的时候卖出,挣的差额,但是要先买入才能卖出
Solutions
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit, min_price = 0, float("inf")
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit