Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- """ How to solve it:
- Use a sliding window (two pointers): the left pointer starts at the first price,
- the right pointer steps forward to try to find the highest price on future days.
- For each new day the right pointer arrives at, update the max-possible profit if
- necessary. If the right pointer finds a new low price, update the left pointer,
- because any future high price will be even more profitable when starting from
- the new low that the right pointer found.
- """
- l = 0
- r = 1
- max_profit = 0
- # We want to keep going as long as the right pointer hasn't hit the end
- while r < len(prices):
- max_profit = max(max_profit, prices[r] - prices[l])
- if prices[r] < prices[l]:
- l = r
- r += 1
- return max_profit
Advertisement
Add Comment
Please, Sign In to add comment