Best Multiplier Streak

Medium · 1-D Dynamic Programming · about 25 min

A game multiplies your score by a whole number each round: nums[i] for round i. The number can be negative (your score flips sign) or zero. Pick one run of consecutive rounds (at least one round) and return the largest product of its numbers.

  • 1 <= len(nums) <= 30000, each number is between -10 and 10.
  • The answer always fits in a 32-bit signed integer.

Examples:

best_product_streak([2, 3, -2, 4]) → 6 (2 × 3)

best_product_streak([-2, 3, -4]) → 24 (the whole run)

Hints

  • The best run ending at round i is built from the run ending at round i - 1, or starts fresh at round i.
  • A very negative product becomes very positive after one more negative number, so the smallest product matters too.
  • Work out the new largest and smallest from the old values at the same time, before you overwrite either.

Learn the pattern first: the 1-D Dynamic Programming lesson.

More 1-D Dynamic Programming problems