Program to find maximum length of subarray with positive product in Python


Suppose we have an array called nums, we have to find the maximum length of a subarray where the product of all its elements is positive. We have to find the maximum length of a subarray with positive product.

So, if the input is like nums = [2,-2,-4,5,-3], then the output will be 4 because first four elements are forming a subarray whose product is positive.

To solve this, we will follow these steps :

  • Define a function util() . This will take s, e
  • neg := 0
  • ns := -1, ne := -1
  • for i in range s to e, do
    • if nums[i] < 0, then
      • neg := neg + 1
      • if ns is same as -1, then
        • ns := i
      • ne := i
  • if neg is even, then
    • return e-s+1
  • otherwise,
    • return maximum of e-ns and ne-s
  • From the main method, do the following −
  • ans := 0
  • s := -1, e := -1
  • for i in range 0 to size of nums, do
    • if nums[i] is not same as 0 and s is same as -1, then
      • s := i
    • otherwise when nums[i] is same as 0 and s is not same as -1, then
      • e := i-1
      • ans := maximum of ans and util(s, e)
      • s := -1, e := -1
  • if s is not same as -1 and e is same as -1, then
    • e := size of nums -1
    • ans := maximum of ans and util(s, e)
  • return ans

Let us see the following implementation to get better understanding:

Example

def util(s, e):
   neg = 0
   ns, ne = -1, -1
   for i in range(s, e+1):
      if nums[i]<0:
         neg += 1
         if ns == -1:
            ns = i
         ne = i

   if neg == 0 or neg %2 == 0:
      return e-s+1
   else:
      return max(e-ns, ne-s)

def solve(nums):
   ans = 0
   s, e = -1, -1

   for i in range(len(nums)):
      if nums[i]!=0 and s == -1:
         s = i
      elif nums[i]==0 and s != -1:
         e = i-1
         ans = max(ans, util(s, e))
         s = -1
         e = -1

   if s!= -1 and e == -1:
      e = len(nums)-1
      ans = max(ans, util(s, e))
      return ans

nums = [2,-2,-4,5,-3]
print(solve(nums))

Input

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

Output

4

Updated on: 04-Oct-2021

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements