ExamAdda Logo

Maximum Product Subarray

Medium

Given an integer array nums, find a contiguous subarray that contains at least one number and has the largest product.

Return the maximum product.

Example 1

Input

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

Output

6

Explanation

The subarray [2, 3] has the maximum product:

2 × 3 = 6

 

Therefore, the answer is 6.

Example 2

Input

nums = [-2, 0, -1]

Output

0

Explanation

The possible products include:

[-2] = -2
[0] = 0
[-1] = -1
[-2, 0] = 0
[0, -1] = 0

Therefore, the maximum product is 0.

Constraints

1 <= n <= 2 * 10^4
-10 <= nums[i] <= 10
The array contains at least one element.

Hints:

Hint 1

For each position, keep track of both:

  • Maximum product ending at the current position.
  • Minimum product ending at the current position.
Hint 2

A negative number can turn the minimum product into the maximum product.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 26, 2026

Last updated

Aug 26, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output