Simple single run Go logic making use of max/min helper funcs


  • 0
    V

    Keep accumulating max and min: out of prev_max * x, prev_min * x, x

    func max(a,b int) int {
        if a > b { return a } return b
    }
    func min(a,b int) int {
        if a < b { return a }  return b
    }
    
    func maxProduct(nums []int) int {
        maxpos, pos, neg := nums[0], nums[0], nums[0]
        
        for _, x := range nums[1:] {
            pos, neg = max(pos * x, max(neg * x, x)), min(pos * x, min(neg * x, x))
            
            maxpos = max(pos, maxpos)
        }
        return max(pos, maxpos)
    }
    

Log in to reply
 

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