152. Maximum Product Subarray

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

subarray is a contiguous subsequence of the array.


Note: How min and max depend on each other.
      This solution uses a, b = f(a, b), f(a, b) python syntax to
avoid needing an explicit temp variable.
Look at the initialization of max_product and running_max, min.



def maxProduct(nums: List[int]):

    max_product = nums[0]
    running_max = 1
    running_min = 1
   
    for i,n in enumerate(nums):
        running_max, running_min = \
            max (n, n*running_max, n*running_min), min (n, n*running_max, n*running_min)
                   
        max_product = max(max_product, running_max)
       
    return max_product

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break