Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Maximum Product Subarray: The Simple Logic
- With **sums**, you just keep adding. With **products**, signs matter:
- - A **negative × negative** becomes **positive** (a tiny number can suddenly become the biggest).
- - A **positive × negative** becomes **negative** (your biggest can suddenly become the smallest).
- - A **zero** wipes everything out.
- So the *smallest* (most negative) product so far can become the *largest* after one more negative number.
- At every position, track **two** values for subarrays ending there:
- - `maxProd`: the biggest product ending here
- - `minProd`: the smallest (most negative) product ending here
- For each new number `x`, there are three choices:
- 1. Start fresh from `x` itself
- 2. Extend the old max: `x * maxProd`
- 3. Extend the old min: `x * minProd` (this helps when `x` is negative)
- ```
- newMax = max(x, x * maxProd, x * minProd)
- newMin = min(x, x * maxProd, x * minProd)
- ```
- Keep a global `answer` = the largest `maxProd` seen at any step.
- ## Dry run: `[2, 3, -2, 4]`
- | x | maxProd | minProd | answer |
- |---|---------|---------|--------|
- | 2 | 2 | 2 | 2 |
- | 3 | 6 | 3 | 6 |
- | -2 | -2 | -12 | 6 |
- | 4 | 4 | -48 | 6 |
- Answer: **6** (subarray `[2, 3]`).
- ## Dry run with two negatives: `[-2, 3, -4]`
- | x | maxProd | minProd | answer |
- |---|---------|---------|--------|
- | -2 | -2 | -2 | -2 |
- | 3 | 3 | -6 | 3 |
- | -4 | 24 | -12 | 24 |
- At `-4`: `minProd (-6) * -4 = 24`. The earlier "bad" negative became the best.
- Note that both new values are computed from the *old* `max_prod` and `min_prod` (that's why `candidates` is built first).
- ## How zeros are handled
- If `x = 0`, all three candidates are `0`, so both `max_prod` and `min_prod` become `0`. The next number then naturally "starts fresh" through choice #1.
- ## Complexity
- - **Time:** O(n), one pass
- - **Space:** O(1), just three variables
- ## One-line summary
- > Track both the biggest and smallest product ending at each position, because a negative number can flip the smallest into the biggest.
- class Solution:
- def maxProduct(self, nums: List[int]) -> int:
- cur_max = cur_min = ans = nums[0]
- for num in nums[1:]:
- temp_max = max(num, num * cur_max, num * cur_min) #Trick is store it in a seprate variable so the cur_min gets the max_till_previous_index accurate.
- cur_min = min(num, num * cur_max, num * cur_min)
- cur_max = temp_max
- ans = max(ans, cur_max)
- return ans
Advertisement
Add Comment
Please, Sign In to add comment