Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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]
- neg := neg + 1
- if ns is same as -1, then
- ns := i
- ne := i
- return e-s+1
- return maximum of e-ns and ne-s
- 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
- e := size of nums -1
- ans := maximum of ans and util(s, e)
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]Input
[2,-2,-4,5,-3]Output
4
Advertisements
