Maximum Product Subarray
1 approach, code in every language
Problem description
Given an integer array, find the contiguous non-empty run of elements whose product is the largest, and return that product. The array may mix positive numbers, negative numbers, and zeros.
Products behave unlike sums because a pair of negatives multiplies into a positive, so a badly small product can suddenly become the best one. That means as you extend the run you have to keep an eye on both the largest and the smallest running product ending at each position.
Example 1
Input: nums = [2,3,-2,4]
Output: 6
The run 2,3 multiplies to 6; the negative value later prevents any longer run from beating it.
Example 2
Input: nums = [-2,3,-4]
Output: 24
Multiplying all three, two negatives cancel out to give 24, which beats any shorter run.
Constraints
1 ≤ nums.length ≤ 2 * 10^4-10 ≤ nums[i] ≤ 10The product of any prefix of the array fits in a 32-bit integer
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Best Multiplier Tile Run is our own problem on the technique behind Maximum Product Subarray: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free