DSA Factory
Free Arrays lessonsArrays · Stage 10 · Mastery · Step 4

Best product

The largest product of a run of numbers, negatives included. About 12 minutes.

Continue or start fresh, with a twist

"Best stretch" problems keep coming back to the same question: does the best stretch ending here continue the one before, or start fresh? With products there's a twist. A negative number flips signs: a big negative product can turn into a big positive one.

So ask: what do I need to remember about the stretches ending just before, if the next number might be negative?

Watch the signs: a negative times a negative is positive.
Best product in [2, 3, -2, 4]
2
0
3
1
-2
2
4
3
i
hi
2
lo
2
best
2

Keep two numbers for runs ending here: the biggest product and the smallest. A negative can flip the smallest into the biggest.

Move 1 of 5
Quick check

The smallest product of a stretch ending at the previous number is −12, and the next number is −2. What product can the stretch reach?

  1. A24
  2. B−2 at best
  3. COnly the previous largest product matters
Show the answer

24. −12 × −2 = 24. That's why the smallest product has to be remembered too.

Your problem

Best product

You get a non-empty list of small whole numbers. Return the largest product of a non-empty run of consecutive numbers.

Example
nums = [2, 3, -2, 4] → 6

1 ≤ n ≤ 15 · −10 ≤ each value ≤ 10 · products fit in a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve