Advertisement
smj007

Untitled

Aug 3rd, 2023
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. class Solution:
  2.    
  3.     def maxProfit(self, prices: List[int]) -> int:
  4.        
  5.         """
  6.        Returns the maximum profit earned
  7.        
  8.        Arguments:
  9.            prices:
  10.        
  11.        Returns:
  12.        
  13.        Notes
  14.        -----
  15.        The problem translates to finding maximum profit which is
  16.        difference of the current price and minimum seen so far.
  17.        It is an optimisation over the brute-force aproach where
  18.        one does not need to determine minimum so far everytime
  19.        """
  20.        
  21.         min_price = float('inf')
  22.         max_profit = float('-inf')
  23.        
  24.         for i in range(len(prices)):
  25.            
  26.             # check for minimum price
  27.             if prices[i] < min_price:
  28.                 min_price = prices[i]
  29.                
  30.             # check condition for max profit
  31.             max_profit_sell_today = prices[i] - min_price
  32.             if max_profit_sell_today > max_profit:
  33.                 max_profit = max_profit_sell_today
  34.            
  35.         return max_profit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement