smj007

Untitled

Jun 19th, 2022
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. class Solution:
  2.     def maxProfit(self, prices: List[int]) -> int:
  3.        
  4.         """
  5.        Notes
  6.        -----
  7.        The problem translates to finding maximum profit which is
  8.        difference of the current price and minimum seen so far.
  9.        It is an optimisation over the brute-force aproach where
  10.        one does not need to determine minimum so far everytime
  11.        """
  12.        
  13.         max_index_so_far = -1
  14.         min_index_so_far = -1
  15.         min_so_far = math.inf
  16.         max_so_far= -math.inf
  17.        
  18.         left, right = 0, 0
  19.         max_profit = 0
  20.        
  21.         for i in range(len(prices)):
  22.            
  23.             if min_so_far >= prices[i]:
  24.                 min_index_so_far = i
  25.                 min_so_far = prices[i]
  26.                
  27.             profit = prices[i] - min_so_far
  28.             if profit > max_profit:
  29.                 max_profit = profit
  30.  
  31.                
  32.         return max_profit
Advertisement
Add Comment
Please, Sign In to add comment