Advertisement
Alexxik

Untitled

Sep 15th, 2023 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.58 KB | None | 0 0
  1. // MARK: - 121  Best Time to Buy and Sell Stock
  2.  
  3. // l - Buy
  4. // r - Sell
  5.  
  6. // Если r < l, то обновляем l, иначе l остается на месте и двигается только r
  7.  
  8. func maxProfit(_ prices: [Int]) -> Int {
  9.     var l = 0
  10.     var r = 1
  11.     var maxProfit = 0
  12.    
  13.     while r < prices.count {
  14.         if prices[r] > prices[l] {
  15.             let profit = prices[r] - prices[l]
  16.             maxProfit = max(maxProfit, profit)
  17.         } else {
  18.             l = r
  19.         }
  20.         r += 1
  21.     }
  22.     return maxProfit
  23. }
  24.  
  25. maxProfit([7,1,5,30,0,6,4])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement