nathanwailes

LeetCode 121 - Best Time to Buy and Sell Stock - 2022.12.27 solution

Dec 26th, 2022
94
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.         """ How to solve it:
  4.        Use a sliding window (two pointers): the left pointer starts at the first price,
  5.        the right pointer steps forward to try to find the highest price on future days.
  6.        For each new day the right pointer arrives at, update the max-possible profit if
  7.        necessary.  If the right pointer finds a new low price, update the left pointer,
  8.        because any future high price will be even more profitable when starting from
  9.        the new low that the right pointer found.
  10.        """
  11.         l = 0
  12.         r = 1
  13.  
  14.         max_profit = 0
  15.        
  16.         # We want to keep going as long as the right pointer hasn't hit the end
  17.         while r < len(prices):
  18.             max_profit = max(max_profit, prices[r] - prices[l])
  19.             if prices[r] < prices[l]:
  20.                 l = r
  21.             r += 1
  22.         return max_profit
Advertisement
Add Comment
Please, Sign In to add comment