algo/leetcode
121. Best Time to Buy and Sell Stock
sourmc
2025. 2. 8. 14:12
121. Best Time to Buy and Sell Stock
It's simple to figure out the days to buy and to sell. Just update the maximum profit iterating over the array of prices.
1. Keep track of the day to buy the stock at the lowest price while iterating over the prices.
2. Maximize the profilt by determining whether to sell or not.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
buy_day = 0
for day, price in enumerate(prices):
if price < prices[buy_day]:
buy_day = day
profit = max(profit, prices[day] - prices[buy_day])
return profit