Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Maximum Product Subarray

Dynamic Programmingmedium

Implement `maxProduct(nums)` returning the largest product of any contiguous subarray.

Sample tests

Input: maxProduct([2,3,-2,4])
Output: 6
Input: maxProduct([-2,0,-1])
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Tracking only the max misses sign flips from negative numbers.

Learning resources

  • Wikipedia: Dynamic programming
Approach & explanation (try first)

Carrying both running max and min handles sign changes in O(n) time, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.