arrays
dynamic-programming
Given an integer array nums, return the largest product you can get from any non-empty contiguous subarray.
Input / output
- Input:
nums: int[] - Output: the maximum product as an integer
Examples
nums = [2, 3, -2, 4]returns6because the best subarray is[2, 3].nums = [-2, 0, -1]returns0because every non-empty subarray has product-2,0, or-1.nums = [-2, 3, -4]returns24because the whole array multiplies to24.
Constraints
1 <= nums.length <= 20000-10 <= nums[i] <= 10- The answer fits in a 32-bit signed integer.
Edge cases
- A negative value can turn the smallest running product into the largest one.
- Zeros split the array into independent segments.
- The best answer may be a single element.
Target complexity
- Aim for
O(n)time andO(1)extra space.
Hints
- Track both the largest and smallest product ending at the current index.
- When the next number is negative, those two running values swap roles.
Follow-up Why is tracking only the current maximum product insufficient once negative numbers are allowed?
Examples
Example 1
Input: nums = [2,3,-2,4]
Output: 6
Example 2
Input: nums = [-2,0,-1]
Output: 0
Example 3
Input: nums = [-2,3,-4]
Output: 24
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.