CodingNodes / 1-D Dynamic Programming / Maximum Product Subarray System design Space play · ←→ step · R restart

Problem

Given an integer array nums, find the non-empty run of consecutive numbers whose product is the largest, and return that product.

The numbers can be negative or zero.

Constraints

  • 1 ≤ nums.length ≤ 9
  • -10 ≤ nums[i] ≤ 10
  • every product fits in a 32-bit integer

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass, a handful of comparisons per number.

Space: Only big, small and best are kept.

A subarray ending at index i either starts at i or extends one that ended at i - 1. A negative number turns the smallest product into the largest, so keep both big and small. For each number compute the two extended products, then big is the max of the number and those two, and small the min. The answer is the best big seen.