Problem 32
Maximum Product Subarray
Medium · 20 pts · Array, Dynamic Programming
Problem
You are given an array of N integers, which may include negative numbers and zeros. Find the largest product of a non-empty block of consecutive elements. Negative numbers make this harder than the maximum sum problem: a very negative product can become the largest one after multiplying by another negative number. So while scanning, keep both the largest and the smallest product of a subarray ending at the current position. A zero resets both.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the maximum product.
Constraints
1 <= N <= 1000; -10 <= A[i] <= 10; the answer fits in a 64-bit signed integer
Example input
4 2 3 -2 4
Example output
6
Explanation
In 2 3 -2 4, the subarray 2 3 has product 6. Including -2 makes the product negative, and 4 alone is only 4, so the answer is 6.