Python – Elements Maximum till current index in List
Last Updated : 01 Jun, 2023
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
test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] print ( "The original list : " + str (test_list)) res = [] for idx in range ( 1 , len (test_list)): cnt = 0 for idx2 in range (idx): if test_list[idx] > test_list[idx2]: cnt = cnt + 1 if cnt = = idx: res.append(test_list[idx]) 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
test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] print ( "The original list : " + str (test_list)) res = [test_list[idx] for idx in range ( 1 , len (test_list)) if test_list[idx] > max (test_list[:idx])] 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
test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] 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) res = [max_list[i] for i in range ( 1 , len (max_list)) if max_list[i] > max_list[i - 1 ]] 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
def find_max_elements_recursive(lst, n): if n = = 1 : return [] max_elements = find_max_elements_recursive(lst, n - 1 ) if all (lst[n - 1 ] > elem for elem in lst[:n - 1 ]): max_elements.append(lst[n - 1 ]) return max_elements test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] print ( "The original list : " + str (test_list)) max_elements = find_max_elements_recursive(test_list, len (test_list)) 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
import functools test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] print ( "The original list : " + str (test_list)) max_list = functools. reduce ( lambda a, b: [a[ 0 ] + [ max (a[ 1 ], b)], max (a[ 1 ], b)], test_list, ([], float ( '-inf' )))[ 0 ] res = [max_list[i] for i in range ( 1 , len (max_list)) if max_list[i] > max_list[i - 1 ]] 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:
- Initialize the list to be processed
- Create an empty list max_list and set the initial maximum value to negative infinity
- 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 - Loop through max_list and append each element that is greater than the previous element to the output list res
- Print the res list
Python3
import numpy as np test_list = [ 3 , 5 , 2 , 6 , 7 , 9 , 3 ] print ( "The original list : " + str (test_list)) arr = np.array(test_list) max_list = np.maximum.accumulate(arr) res = [max_list[i] for i in range ( 1 , len (max_list)) if max_list[i] > max_list[i - 1 ]] 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)
Similar Reads
Python - K Maximum elements with Index in List
GIven a List, extract K Maximum elements with their indices. Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2 Output : [(4, 7), (5, 8)] Explanation : 8 is maximum on index 5, 7 on 4th. Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1 Output : [(5, 10)] Explanation : 10 is maximum on index 5. Method
4 min read
Python - Maximum element in Cropped List
Sometimes, while working with Python, we can have a problem in which we need to get maximum of list. But sometimes, we need to get this for between custom indices. This can be need of any domain be it normal programming or web development. Let's discuss certain ways in which this task can be perform
4 min read
Python | Maximum element in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: U
6 min read
Python | Get elements till particular element in list
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let's discuss certain ways in
7 min read
Python - Assign keys with Maximum element index
Given Dictionary with value lists, the task is to write a Python program to assign each key with an index of the maximum value in the value list. Examples: Input : test_dict = {"gfg" : [5, 3, 6, 3], "is" : [1, 7, 5, 3], "best" : [9, 1, 3, 5]} Output : {'gfg': 2, 'is': 1, 'best': 0} Explanation : Max
4 min read
Python | Minimum element in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 :
5 min read
Python - Every Kth index Maximum in List
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Letâs discuss certain ways in which maximum of these el
4 min read
Python - Ranged Maximum Element in String List
Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
5 min read
Python - Key with Maximum element at Kth index in Dictionary Value List
Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list. Input : test_dict = {'Gfg' : [4, 6, 8, 2], 'is' : [1, 4, 5, 9], 'best' :[2, 3, 4, 10], 'for' :[4, 5, 2, 1], 'geeks' :[2, 10,
8 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3. Using index()index() method in Python searches for the first occu
3 min read