Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Product behaves differently than sum due to negatives.
- A negative can turn a small (min) product into a large (max) one if the current element is also negative.
- So at each index, track:
- - max product so far from (num, num*cur_max, num*cur_min)
- - min product so far
- Update both using current number, and keep global max as ans.
- """
- from typing import List
- 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)
- 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