Skills101
← All coding problems

Maximum Product Subarray

mediumDynamic Programming+20 XPTime limit 2s

Find the largest product of a non-empty contiguous subarray.

Input:

  • line 1: n
  • line 2: n integers

Output: the maximum product.

Constraints: 1 ≤ n ≤ 10⁵, −10 ≤ a[i] ≤ 10. Every subarray's product fits in a signed 64-bit integer.

Think about it: a negative number turns the smallest product into the largest. So track both the maximum and the minimum product ending at each position; at x, the new values come from x, max·x and min·x. Zeros reset everything.

Sample input 1

4
2 3 -2 4

Sample output 1

6

Sample input 2

3
-2 0 -1

Sample output 2

0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.