Open In App

Python – Elements Maximum till current index in List

Last Updated : 01 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given list with elements, extract element if it’s the maximum element till current index.

Input  :  test_list = [4, 6, 7, 8]

Output : [4, 6, 7, 8]

Explanation :  All elements are maximum till their index.

Input  :  test_list = [6, 7, 3, 6, 8, 7]

Output : [7, 8]

Explanation :  7 and 8 are maximum till their index.

Method #1 : Using loop

This is brute method in which this task can be performed. In this, we run nested loop till current index and increment the counter if all elements are lower than current element, if counter matches the current index, suggests that current element is maximum till current index.

Python3




# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using loop
 
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using loop
res = []
for idx in range(1, len(test_list)):
    cnt = 0
 
    # inner loop to count element less than current
    for idx2 in range(idx):
        if test_list[idx] > test_list[idx2]:
            cnt = cnt + 1
    if cnt == idx:
        res.append(test_list[idx])
 
# printing result
print("Extracted Maximum elements : " + str(res))


Output

The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

Method #2 : Using max() + list comprehension + list slicing

The combination of above functions can be used to solve this problem. In this, we use max() to check if current element is greater that all previous elements extracted using list slicing.

Python3




# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using max() + list comprehension + list slicing
 
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using max() + list comprehension + list slicing
# max() used to get if current is current maximum
res = [test_list[idx] for idx in range(
    1, len(test_list)) if test_list[idx] > max(test_list[:idx])]
 
# printing result
print("Extracted Maximum elements : " + str(res))


Output

The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

Method #3: Using a for loop and an additional list to keep track of maximum elements

This method uses a for loop to iterate over the elements of the input list, and an additional list max_list to keep track of the maximum element seen so far. current_max is initialized to negative infinity, and is updated whenever a new maximum element is found. The list comprehension at the end is similar to method #2, but instead of using max() on a slice of the input list, it uses the max_list to check if the current element is the maximum so far.

Python3




# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
max_list = []
current_max = float('-inf')
for i in range(len(test_list)):
    if test_list[i] > current_max:
        current_max = test_list[i]
    max_list.append(current_max)
 
# Extracting Maximum elements
res = [max_list[i] for i in range(1, len(max_list)) if max_list[i] > max_list[i-1]]
 
# printing result
print("Extracted Maximum elements : " + str(res))


Output

The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

Time complexity: O(n)
Auxiliary space: O(n)

Method#4: Using Recursive method.

The get_max_elements function is a recursive function that takes two parameters: lst, which is the input list, and idx, which is the current index of the list. The function returns a list of maximum elements up to the current index.

In the base case, when the current index is 0, the function returns an empty list.

In the recursive case, the function first calls itself with the current index decremented by 1 to get the list of maximum elements up to the previous index. Then, the function checks how many elements in the list are less than the element at the current index. If all the previous elements are less than the current element, the current element is added to the list of maximum elements.

Python3




# Python3 code to demonstrate working of
# Elements Maximum till current index in List
# Using recursion
 
# Function to find the maximum elements
# till current index recursively
def find_max_elements_recursive(lst, n):
    # Base case: when the list has only one element
    if n == 1:
        return []
 
    # Recursively find the maximum elements till the previous index
    max_elements = find_max_elements_recursive(lst, n-1)
 
    # Check if the current element is greater than all the previous elements
    if all(lst[n-1] > elem for elem in lst[:n-1]):
        max_elements.append(lst[n-1])
 
    return max_elements
 
# Initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# Printing original list
print("The original list : " + str(test_list))
 
# Finding maximum elements till current index using recursion
max_elements = find_max_elements_recursive(test_list, len(test_list))
 
# Printing result
print("Extracted Maximum elements : " + str(max_elements))


Output

The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

The time complexity of this recursive method is O(n^2), where “n” is the length of the input list, as the function checks all the previous elements for each index. 

The auxiliary space is also O(n), as the function uses a list to store the maximum elements up to each index.

Method #5: Using the reduce() function from the functools module

Step by step approach:

Import the functools module
Define a lambda function that takes two arguments (current maximum, current value) and returns the maximum of the two.
Use the reduce() function to apply the lambda function to each element in the test_list and accumulate the maximum value so far in a list called max_list.
Use a list comprehension to extract the maximum elements from max_list by comparing each element with the one before it.
Print the extracted maximum elements.

Python3




# importing functools module
import functools
 
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using reduce() function to accumulate the maximum values
max_list = functools.reduce(lambda a, b: [a[0] + [max(a[1], b)], max(a[1], b)], test_list, ([], float('-inf')))[0]
 
# Extracting Maximum elements
res = [max_list[i] for i in range(1, len(max_list)) if max_list[i] > max_list[i-1]]
 
# printing result
print("Extracted Maximum elements : " + str(res))


Output

The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

Time complexity: O(n)
Auxiliary space: O(n)

Method #6: Using numpy:

Algorithm:

  1. Initialize the list to be processed
  2. Create an empty list max_list and set the initial maximum value to negative infinity
  3. Loop through the elements of the list and for each element:
    a. If the element is greater than the current maximum value, append it to max_list
    b. Set the maximum value to the larger of the current maximum value and the current element
  4. Loop through max_list and append each element that is greater than the previous element to the output list res
  5. Print the res list

Python3




import numpy as np
 
# initializing list
test_list = [3, 5, 2, 6, 7, 9, 3]
 
# printing original list
print("The original list : " + str(test_list))
 
# Converting list to numpy array
arr = np.array(test_list)
 
# Using numpy's maximum filter to get the maximum value in each window
max_list = np.maximum.accumulate(arr)
 
# Extracting Maximum elements
res = [max_list[i] for i in range(1, len(max_list)) if max_list[i] > max_list[i-1]]
 
# printing result
print("Extracted Maximum elements : " + str(res))


Output:
The original list : [3, 5, 2, 6, 7, 9, 3]
Extracted Maximum elements : [5, 6, 7, 9]

Time Complexity: O(n)

The algorithm loops through the input list once to create max_list, which has a worst case length of n
The algorithm loops through max_list once to create res, which has a worst case length of n
Thus, the overall time complexity of the algorithm is O(n)
Space Complexity: O(n)

The algorithm creates two additional lists max_list and res, each of which has a worst case length of n
Thus, the overall space complexity of the algorithm is O(n)



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

Similar Reads