Open In App

Python – Maximum length consecutive positive elements

Last Updated : 04 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we monitor a sequence and we need to find what was the maximum length when just positive elements occur. This kind of problem can have applications in data domains. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [4, 5, 4, 1, 7, 2, 5, 6, -2, -9, -10] 
Output : 8 

Input : test_list = [4, -5, -4, -1, -7, 2, 5, -6, -2, -9, -10] 
Output : 2

Method #1: Using loop This is one of the way in which we perform this task. In this brute force way, we iterate for all the elements and keep on updating max, whenever the positive elements chain is broken. 

Python3




# Python3 code to demonstrate working of
# Maximum length consecutive positive elements
# Using loop
 
# initializing list
test_list = [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10]
 
# printing original list
print("The original list : " + str(test_list))
 
# Maximum length consecutive positive elements
# Using loop
counter = 0          
max_score = 1
for ele in test_list:
    if ele > 0:
        counter += 1
    else:
        if(counter > 0):
            max_score = max(max_score, counter)
        counter = 0
if(counter > 0):
        max_score = max(max_score, counter)
 
# printing result
print("Maximum elements run length : " + str(max_score))


Output : 

The original list : [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10]
Maximum elements run length : 3

Time complexity: O(n), where n is the length of the input list ‘test_list’, since the program has to iterate through each element of the list once.
Auxiliary space: O(1), because it only uses a fixed amount of additional space, regardless of the input size. Specifically, it uses two integer variables (‘counter’ and ‘max_score’) to store temporary values during the iteration.

Method #2: Using groupby() + defaultDict() + max() The combination of above functions can be used to solve this problem. In this, we perform the task of grouping using groupby(), we can perform the task of finding max of both negative and positive maximum run by grouping them against different keys, and using max() to find maximum of list at end. 

Python3




# Python3 code to demonstrate working of
# Maximum length consecutive positive elements
# Using groupby() + defaultDict() + max()
from collections import defaultdict
from itertools import groupby
 
# initializing list
test_list = [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10]
 
# printing original list
print("The original list : " + str(test_list))
 
# Maximum length consecutive positive elements
# Using groupby() + defaultDict() + max()
counter = defaultdict(list)
for key, val in groupby(test_list, lambda ele: "plus" if ele >= 0 else "minus"):
    counter[key].append(len(list(val)))
res = []
for key in ('plus', 'minus'):
    res.append(counter[key])
 
# printing result
print("Maximum elements run length : " + str(max(res[0])))
print("Maximum negative elements run length : " + str(max(res[1])))


Output : 

The original list : [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10]
Maximum elements run length : 3
Maximum negative elements run length : 3

Time complexity: O(n log n), where n is the length of the input list
Auxiliary space: O(n), where n is the length of the input list. 

Iterative approach to find the maximum length of consecutive positive elements

Steps:

  1. Initialize a current length variable and a maximum length variable to zero.
  2. Iterate over the elements of the given list.
  3. If the element is positive, increment the current length variable by 1. If it is non-positive, reset the current length variable to zero.
  4. Update the maximum length variable if the current length becomes greater than it.
  5. Return the maximum length variable.

Python3




def max_consecutive_positives(lst):
    curr_len = 0
    max_len = 0
    for num in lst:
        if num > 0:
            curr_len += 1
        else:
            curr_len = 0
        max_len = max(max_len, curr_len)
    return max_len
 
test_list = [4, 5, 4, 1, 7, 2, 5, 6, -2, -9, -10]
print(max_consecutive_positives(test_list))  # Output: 8


Output

8

Time Complexity: O(n), where n is the length of the input list.

Auxiliary Space: O(1).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads