Simple Swift solution with O(n) complexity


  • 0
    S

    The solution is too simple to explain!

    func maxProfit(_ prices: [Int]) -> Int {
            guard prices.count > 1 else { return 0 }
            var profit = 0
            for i in 0..<prices.count-1 {
                let diff = prices[i+1] - prices[i]
                if diff > 0 {
                    profit += diff 
                }
            }
            return profit
        }
    

Log in to reply
 

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