Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 121 Best Time to Buy and Sell Stock
- // l - Buy
- // r - Sell
- // Если r < l, то обновляем l, иначе l остается на месте и двигается только r
- func maxProfit(_ prices: [Int]) -> Int {
- var l = 0
- var r = 1
- var maxProfit = 0
- while r < prices.count {
- if prices[r] > prices[l] {
- let profit = prices[r] - prices[l]
- maxProfit = max(maxProfit, profit)
- } else {
- l = r
- }
- r += 1
- }
- return maxProfit
- }
- maxProfit([7,1,5,30,0,6,4])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement