My Golang solution O(n)time & O(1) space


  • 0
    func maxProfit(prices []int) int {
        if prices == nil || len(prices) == 1 {
            return 0
        }
        profit := 0
        for i := 1; i < len(prices); i++ {
            delta := prices[i] - prices[i-1]
            if delta > 0 {
                profit += delta
            }
        }
        return profit
    }
    

Log in to reply
 

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