Maximum Product Subarray GFG Question Python

Question:

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.

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
Asked By: Ahmed Dulap

||

Answers:

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
Answered By: Pratul Pant
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.