Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Maximum Product Subarray GFG Question Python

I was practising DSA questions.

Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray.

I am unable to complete this code. Please check the code and help. Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def maxSubarrayProduct(arr, n):
  
        result = arr[0]
  
        for i in range(n):
      
            mul = arr[i]
        
            for j in range(i + 1, n):
          
                result = max(result, mul)
                mul *= arr[j]
          
            result = max(result, mul)
      
        return result

>Solution :

I think the program you wrote comes under brute force methods which have the worst time complexity. To improve its time and space complexity you can just make 2 variables that will store your current max and current min value. Here is the code for reference. Happy coding. Let me know if this helps.

def maxProduct(self,arr, n):
        res = max(arr)
        currMax, currMin = 1,1
        
        for i in arr:
            if i == 0:
                currMax, currMin = 1,1
                continue
            #Storing max value to use it later on.
            temp = currMax*i
            currMax = max(currMax*i, currMin*i, i)
            currMin = min(currMin*i, temp, i)
            
            res = max(res, currMax)
        
        return res
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading