My Swift solution - O(n) time & O(1) space


  • 0
    class Solution {
        func maxProfit(_ prices: [Int]) -> Int {
            if prices.count == 0 || prices.count == 1 {
                return 0
            }
            
            var max = 0
            
            for i in 0..<prices.count - 1 {
                if prices[i] < prices[i + 1] {
                    max += (prices[i + 1] - prices[i])
                }
            }
            
            return max
        }
    }
    

Log in to reply
 

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