Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The largest product of a subarray

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonMicrosoftLinkedIn

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

Examples

InputOutputWhy
nums = [2,3,-2,4]62 · 3.
nums = [-2,3,-4]24Two negatives make a positive.
nums = [-2,0,-1]0The zero on its own.

Constraints

  • 1 ≤ nums.length ≤ 2 · 10⁴
  • −10 ≤ nums[i] ≤ 10
  • Every product fits in a 64-bit integer

Hints

Hint 1

The best product ending here could come from the worst product ending at the previous position, if the current number is negative.

Hint 2

Keep hi and lo: the largest and smallest products ending at i.

Hint 3

hi, lo = max(x, hi·x, lo·x), min(x, hi·x, lo·x).

Where people lose marks

  • Tracking only the maximum, which fails on [−2, 3, −4].
  • Updating hi before computing the new lo from the old hi.
  • Starting the answer at 0 or 1 rather than at nums[0].
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.