imashutosh51

Maximum product subarray

Oct 8th, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. """
  2. Product behaves differently than sum due to negatives.
  3. A negative can turn a small (min) product into a large (max) one if the current element is also negative.
  4.  
  5. So at each index, track:
  6. - max product so far from (num, num*cur_max, num*cur_min)
  7. - min product so far
  8.  
  9. Update both using current number, and keep global max as ans.
  10. """
  11.  
  12. from typing import List
  13.  
  14. class Solution:
  15.     def maxProduct(self, nums: List[int]) -> int:
  16.         cur_max = cur_min = ans = nums[0]
  17.        
  18.         for num in nums[1:]:
  19.             temp_max = max(num, num * cur_max, num * cur_min)
  20.             cur_min = min(num, num * cur_max, num * cur_min)
  21.             cur_max = temp_max
  22.            
  23.             ans = max(ans, cur_max)
  24.        
  25.         return ans
Advertisement
Add Comment
Please, Sign In to add comment