Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the maximum product subarray

Compute the maximum product obtainable from a contiguous subarray.

Python practice30 minArrays – Fundamentals & PatternsAdvancedLast updated March 25, 2026

Problem statement

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest product and return that product. The array may contain positive numbers, negative numbers, and zeros. Implement an O(n) time and O(1) extra space solution.

Task

Track both maximum and minimum running products to handle negative values and zeros, returning the maximum subarray product.

Examples

Example with negative

Input

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

Output

6

Subarray [2,3] gives product 6, which is maximal.

Input format

Function signature: max_product_subarray(nums: list[int]) -> int

Output format

Return an integer: the maximum product of any contiguous subarray.

Constraints

1 <= len(nums) <= 10^5, -10^9 <= nums[i] <= 10^9. Expected O(n) time and O(1) space.

Samples

Sample 1

Input

nums = [-2, 0, -1]

Output

0

Maximum product achievable is 0 (single element subarray [0]).