Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Maximum element in Cropped List
Next article icon

Python – Elements Maximum till current index in List

Last Updated : 01 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Python - Maximum element in Cropped List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python loop-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences