Maximum Product Subarray in Python


Suppose we have an integer array called nums, we have to find the contiguous subarray within an array (containing at least one number) which has the largest product. So if the array is [2,3,-2,4], the output will be 6, as contiguous subarray [2,3] has max product.

To solve this, we will follow these steps −

  • max_list := list of size nums, and fill with 0

  • min_list := list of size nums, and fill with 0

  • max_list[0] := nums[0] and min_list[0] := nums[0]

  • for i in range 1 to length of nums

    • max_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]

    • min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]

  • return the max of max_list

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def maxProduct(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      max_list = [0] * len(nums)
      min_list = [0] * len(nums)
      max_list[0] = nums[0]
      min_list[0] = nums[0]
      for i in range(1,len(nums)):
         max_list[i] = max(max(max_list[i-1]*nums[i],min_list[i-1]*nums[i]),nums[i])
         min_list[i] = min(min(min_list[i-1]*nums[i],nums[i]),max_list[i-1]*nums[i])
      return max(max_list)

Input

[2,3,-2,4,-5,-6,2]

Output

240
raja
Published on 03-Feb-2020 10:59:25
Advertisements