~/problems / 1-D dynamic programming / Intro DP

Maximum Product Subarray

medium ~25 min

Given a list of integers nums, return the largest product of any non-empty contiguous run of elements.

Write max_product(nums: list[int]) -> int.

max_product([2, -3, -2, 4])  # 48   the whole list: the two negatives cancel
max_product([-4, 3, -2])     # 24
max_product([-2, 0, -1])     # 0    a run holding just the 0
max_product([3, -1, 4])      # 4
max_product([-5])            # -5   the run can't be empty

Constraints: 1 <= len(nums) <= 10^5, -10 <= nums[i] <= 10, and the product of every contiguous run fits in a signed 64-bit integer.

Checking every (start, end) pair is O(n²), too slow here; aim for O(n) time and O(1) extra space.

Show hint

Multiplying by a negative number turns the smallest product into the largest one. For each end position, track both the largest and the smallest product of a run ending there.

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc