Back to Practice
#0198
Maximum Product Subarray
MediumDSA25 min20 XP
Problem
Return the maximum product of any contiguous non-empty subarray.
Why This Matters
Negative numbers make product problems different from sum problems: a very small negative product can become the best positive product later.
Function Signature
def max_product_subarray(nums):
Examples
Example 1
Input[2, 3, -2, 4]
Output6
The subarray [2, 3] has product 6, which is larger than using the negative value.
Constraints
- Return the exact requested result.
- Handle common edge cases.
- Keep the solution readable before optimizing.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input[2, 3, -2, 4]
Expected6
The subarray [2, 3] has product 6, which is larger than using the negative value.
Hidden Test Categories
empty or minimal inputrepeated valueslarger realistic input