A simple solution written in Python, O(n) time, O(1) space


  • 0
    D
    class Solution:
        # @param {integer[]} nums
        # @return {integer}
        def maxProduct(self, nums):
            init = 0
            if 0 not in nums:
                init = min(nums)
            a1, a2 = init, 1
            b1, b2 = init, 1
    
            for i in nums:
                a2 *= i
                if a2 == 0:
                    a2 = 1
                else:
                    if a2 > a1:
                        a1 = a2
    
            for i in nums[-1::-1]:
                b2 *= i
                if b2 == 0:
                    b2 = 1
                else:
                    if b2 > b1:
                        b1 = b2
            return max(b1, a1)

Log in to reply
 

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