MediumArraysDynamic ProgrammingSliding Window

Maximum Product Subarray

LeetCode
1 approach, code in all languages

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] ≤ 10
  • The product of any prefix of the array fits in a 32-bit integer
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now