Menu
CoddyTech

Maximum Product Subarray

Multiply the elements of a subarray of nums together, and return the largest product any subarray can give. A subarray takes consecutive elements without gaps and is never empty, so even an array of negatives has an answer. Zeros and negative values are allowed.

Function

maxProduct(nums: integer-array) → integer
numsinteger-array
the integers to multiply, each between -10 and 10
Returnsinteger
the largest product of a non-empty subarray

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -10 ≤ nums[i] ≤ 10
  • The product of every subarray fits in a 32-bit signed integer.

Examples

Input
nums = [2, -5, 3, -2, 0, 4]
Output
60
Explanation
The two negatives cancel: 2 × -5 × 3 × -2 = 60. The 0 cuts the array in two, and the 4 on the other side cannot beat 60.
challenge icon

Follow-up

How would you also report where the best subarray starts and ends, still in O(n) time and O(1) space?

Reset code
def maxProduct(nums):
    # Write code here

Test #1

Test #2

Test #3

Argument

nums = [2, -5, 3, -2, 0, 4]

Expected Output

60