Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N.
Input : [4, 5, 1, 2, 9] N = 2 Output : [9, 5] Input : [81, 52, 45, 10, 3, 2, 96] N = 3 Output : [81, 96, 52]
A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation :
Time Complexity : O(N * size) where size is size of the given list.
[-45, 100, 200, 298, 900, 1000, 3579] Find the N largest element: 4 [298, 900, 1000, 3579]
Please refer k largest(or smallest) elements in an array for more efficient solutions of this problem.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course