AlgoFrames

Maximum product subarray

Challenge · Write code · about 20 min

Return the largest product of a contiguous, non-empty subarray of nums.

The answer fits in a 32-bit signed integer.

Example 1

Input:

[[2,3,-2,4]]

Output:

6

2 × 3 = 6.

Example 2

Input:

[[-2,3,-4]]

Output:

24

Two negatives: −2 × 3 × −4 = 24.

Constraints

  • 1 ≤ nums.length ≤ 2,000
  • −10 ≤ nums[i] ≤ 10
  • Every subarray product fits in a 32-bit signed integer

Learn the idea first: Kadane's algorithm and maximum subarray, a visual lesson.

More Kadane's algorithm and maximum subarray problems