Find the maximum product of any contiguous subarray in an integer array.
Problem
Given an integer array nums, find the maximum possible product of a non-empty contiguous subarray.
A subarray is a contiguous slice of the array. The answer may be positive, zero, or negative, depending on the values in the array, but you should return the largest product that can be obtained from any contiguous segment.
Goal
Choose a contiguous block of elements whose product is as large as possible and return that product.
Input Format
- A single integer array
nums. nums[i]is an integer value for the -th element.
Output Format
- Return a single integer: the maximum product over all non-empty contiguous subarrays of
nums.
Constraints
- The array is non-empty.
- Values may be positive, negative, or zero.
- The product may exceed 32-bit integer range in some languages, so use an appropriate numeric type if needed.
Example 1
Input
nums = [2,3,-2,4]
Output
6
Explanation
The subarray [2,3] has product 6, which is larger than the products of all other contiguous subarrays.
Example 2
Input
nums = [-2,0,-1]
Output
0
Explanation
The best choice is [0], whose product is 0.
Show 1 more example
Example 3
Input
nums = [-2,3,-4]
Output
24
Explanation
The whole array has product 24. The negative numbers flip the sign, so keeping track of both best and worst running products is important.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.