Maximum Product Subarray
Problem statement
Given a nonempty integer array nums, return the largest product obtainable by multiplying every element in one nonempty contiguous subarray.
A contiguous subarray uses consecutive elements of nums. You may choose a single element, and the array may contain negative numbers and zeros.
Return the product value, rather than the chosen subarray or its indices. Products are exact signed integers; do not apply a modulus.
Function
maxProduct(nums: int[]) → longExamples
Example 1
nums = [2,3,-2,4]return = 6The subarray [2,3] has product 6. Any subarray containing -2 has a negative product, and the remaining singleton [4] has product 4.
Example 2
nums = [-2,3,-4]return = 24The entire array is contiguous, and its product is (-2) * 3 * (-4) = 24. The two negative factors produce a positive product.
Example 3
nums = [-2,0,-1]return = 0The singleton [0] has product 0, larger than either negative singleton. The values -2 and -1 cannot be multiplied together without including the intervening zero.
Constraints
1 <= nums.length <= 10^5.-10 <= nums[i] <= 10.- The product of every nonempty contiguous subarray is guaranteed to lie between
-10^18and10^18, inclusive. - The returned value must use a signed
64-bitinteger or a wider exact integer type.