837. Find the largest product of a contiguous run
You log a multiplicative change factor for every training step, as whole numbers that can be positive, zero or negative. You want the contiguous run of steps whose factors multiply to the largest value.
Write max_product_run(nums) that returns the largest product of any non-empty contiguous slice of nums.
def max_product_run(nums)Example 1
Input: max_product_run([2, 3, -2, 4])
Output: 6, from the slice [2, 3]
Example 2
Input: max_product_run([-2, 3, -4])
Output: 24
Explanation: Because two negatives multiply to a positive.
Constraints
- 1 <=
len(nums)<= 20,000 - Each value is an integer between -10 and 10.
Hint 1
Keep the max and the min product ending at the current index.
Hint 2
Negative x swaps the roles of max and min.
Hint 3
Start every state from nums[0], not from 1 or 0.
Common mistakes
- Starting best at 0, which is wrong for [-5].
- Updating
cur_maxfirst and then using the new value to computecur_min. - Forgetting that x alone can beat any extended slice after a zero.
Understand the idea
This is Kadane style dynamic programming with two states instead of one. For sums, the best slice ending at i only needs the best slice ending at i - 1. For products, sign flips mean you also need the worst (most negative) slice ending at i - 1, since multiplying it by a negative number can make it the best. With [-2, 3, -4]: after -2 the pair is (max -2, min -2); after 3 it is (3, -6); after -4 it becomes (24, -12), giving 24.