swift, o(n) time, save max and min price


  • 0
    X
    class Solution {
        func maxProfit(_ prices: [Int]) -> Int {
            if prices.count < 1 { return 0 }
            
            var maxProfit = 0, minPrice = prices[0]
            for price in prices {
                if(price < minPrice){ minPrice = price }
                if (price - minPrice) > maxProfit {
                    maxProfit = price - minPrice
                }
            }
            return maxProfit
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.