Advertisement
smj007

Untitled

Apr 7th, 2025
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. # same tc and sc for both - however -
  2.  
  3. class Solution:
  4.     def maxProfit(self, prices: List[int]) -> int:
  5.         max_profit = 0
  6.         recent_valley = prices[0]
  7.         recent_peak = prices[0]
  8.         i = 0
  9.  
  10.         while i < len(prices)-1:
  11.             #find valley first
  12.             while i < len(prices)-1 and prices[i+1]<=prices[i]:
  13.                 i += 1
  14.             recent_valley = prices[i]
  15.            
  16.             # find peak then
  17.             while i < len(prices)-1 and prices[i+1]>=prices[i]:
  18.                 i += 1
  19.             recent_peak = prices[i]
  20.  
  21.             # calculate profit
  22.             max_profit += recent_peak - recent_valley
  23.  
  24.         return max_profit
  25.  
  26.  
  27. class Solution:
  28.     def maxProfit(self, prices: List[int]) -> int:
  29.         max_profit = 0
  30.  
  31.         for i in range(1, len(prices)):
  32.             if prices[i] > prices[i-1]:
  33.                 max_profit += prices[i] - prices[i-1]
  34.  
  35.         return max_profit
  36.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement