smj007

Best time to buy and sell stock

Aug 31st, 2025
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.54 KB | None | 0 0
  1. class Solution:
  2.     def maxProfit(self, prices: List[int]) -> int:
  3.  
  4.         min_price_so_far = float("inf")
  5.         max_profit = -float("inf")
  6.  
  7.         for i in range(len(prices)):
  8.             if prices[i] - min_price_so_far >=0:
  9.                 max_profit_so_far = prices[i] - min_price_so_far
  10.                 max_profit = max(max_profit, max_profit_so_far)
  11.             min_price_so_far = min(prices[i], min_price_so_far)
  12.  
  13.         # also care for edge case when low prices are never observed
  14.         return max_profit if max_profit>0 else 0
Advertisement
Add Comment
Please, Sign In to add comment