Advertisement
Iam_Sandeep

Maximum Product Subarray

Jul 2nd, 2022 (edited)
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. class Solution:
  2.     def maxProduct(self, nums: List[int]) -> int:
  3.         ans=float('-inf')
  4.         pos,neg,ans=1,1,max(nums)
  5.         for i in nums:
  6.             temp=pos
  7.             pos=max(pos*i,neg*i,i)
  8.             '''
  9.            For e.g. [-1,8] To avoid -8 as final answer we use third parameter.
  10.             So if array starts with negative number this third parameter helps out 
  11.            '''
  12.             neg=min(temp*i,neg*i,i)
  13. '''
  14. Here we are including third parameter.
  15. If we dont include third parameter,
  16. for e.g. if array contains  all positive numbers error occurs.
  17. '''
  18.      
  19.             ans=max(pos,ans)#Here update max with pos and ans .(VVVimp)
  20.         return ans
  21.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement