Given an array of integers nums, find the subarray that produces the maximum product and return that product.
A subarray is a contiguous, non-empty sequence of elements within an array.
Assume the output fits within a 32-bit integer.
Function Signature
def max_product(nums: list[int]) -> int:
Rules
-
The subarray must contain at least one element. An empty subarray (with product 1) is not allowed.
-
Return only the product, as an integer. The subarray itself is not returned.
Constraints
-
1 <= len(nums) <= 10^4
-
-15 <= nums[i] <= 15
-
The answer fits in a signed 32-bit integer.
Examples
Input: nums = [2, -5, -2, -4, 3]
Output: 24
The subarray [-2, -4, 3] has product (-2) * (-4) * 3 = 24. Adding -5 to it makes the product negative, and [2, -5, -2] reaches only 20.
Input: nums = [0, -1, 0]
Output: 0
Every subarray that contains a 0 has product 0, and the only other subarray, [-1], has product -1.
Input: nums = [-3]
Output: -3
The only non-empty subarray is [-3], so the answer is negative.