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
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
C++ Program to Find Largest Element in an Array
Next article icon

C++ Program to Find k maximum elements of array in original order

Last Updated : 17 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.
Note : k is always less than or equal to n.

Examples:  

Input : arr[] = {10 50 30 60 15}          k = 2  Output : 50 60  The top 2 elements are printed  as per their appearance in original  array.    Input : arr[] = {50 8 45 12 25 40 84}              k = 3  Output : 50 45 84

Method 1: We search for the maximum element k times in the given array. Each time we find one maximum element, we print it and replace it with minus infinite (INT_MIN in C) in the array. The time complexity of this method is O(n*k).

C++
// C++ program to find k Maximum elements #include <bits/stdc++.h> using namespace std;  // Function to print k Maximum elements void printMax(int a[], int n, int k) {     int b[n],c[n];          // Coping the array a     // into c and initialising     // elements in array b as 0.     for(int i=0;i<n;i++)     {         c[i]=a[i];         b[i]=0;     }          // Iterating for K-times     // to find k-maximum     for(int i=0;i<k;i++)     {         // finding the maximum element         // and its index         int maxi=INT_MIN;         int index;         for(int j=0;j<n;j++)         {             if(a[j]>maxi)             {                 maxi=a[j];                 index=j;             }         }         // Assigning 1 in order         // to mark the position         // of all k maximum numbers         b[index]=1;         a[index]=INT_MIN;     }          for(int i=0;i<n;i++)     {         // Printing the k maximum         // elements of the array         if(b[i]==1)         cout<<c[i]<<" ";     } }  // Driver code int main() {     int a[] = { 50, 8, 45, 12, 25, 40, 84 };     int n = sizeof(a) / sizeof(a[0]);     int k = 3;     printMax(a, n, k);     return 0; }  // This code is contributed by Aman kumar. 

Output
50 45 84 

Time Complexity: O(n*k)
Auxiliary Space: O(n)

Method 2: In this method, we store the original array in a new array and will sort the new array in descending order. After sorting, we iterate the original array from 0 to n and print all those elements that appear in first k elements of new array. For searching, we can do Binary Search.

C++
// C++ program to find k maximum elements  // of array in original order #include <bits/stdc++.h> using namespace std;  // Function to print m Maximum elements void printMax(int arr[], int k, int n) {     // vector to store the copy of the     // original array     vector<int> brr(arr, arr + n);      // Sorting the vector in descending     // order. Please refer below link for     // details     // https://www.geeksforgeeks.org/sort-c-stl/     sort(brr.begin(), brr.end(), greater<int>());      // Traversing through original array and     // printing all those elements that are     // in first k of sorted vector.     // Please refer https://goo.gl/44Rwgt     // for details of binary_search()     for (int i = 0; i < n; ++i)         if (binary_search(brr.begin(),                  brr.begin() + k, arr[i],                          greater<int>()))             cout << arr[i] << " "; }  // Driver code int main() {     int arr[] = { 50, 8, 45, 12, 25, 40, 84 };     int n = sizeof(arr) / sizeof(arr[0]);     int k = 3;     printMax(arr, k, n);     return 0; } 

Output: 

50 45 84 


Time Complexity: O(n Log n) for sorting. 
Auxiliary Space: O(n)
 

Please refer complete article on Find k maximum elements of array in original order for more details!


Next Article
C++ Program to Find Largest Element in an Array
author
kartik
Improve
Article Tags :
  • Searching
  • Sorting
  • C++ Programs
  • C++
  • DSA
  • Binary Search
  • STL
  • cpp-vector
Practice Tags :
  • CPP
  • Binary Search
  • Searching
  • Sorting
  • STL

Similar Reads

  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • C++ Program to Find maximum element of each row in a matrix
    Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : The approach is very simple. The idea is to run the loop for no_of_rows. Check each
    2 min read
  • How to Find the Maximum Element of an Array using STL in C++?
    Given an array of n elements, the task is to find the maximum element using STL in C++. Examples Input: arr[] = {11, 13, 21, 45, 8}Output: 45Explanation: 45 is the largest element of the array. Input: arr[] = {1, 9, 2, 5, 7}Output: 9Explanation: 9 is the largest element of the array. STL provides th
    3 min read
  • C++ Program to Find the Second Largest Element in an Array
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
    3 min read
  • C++ Program to Find the K'th largest element in a stream
    Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input:stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...}k = 3Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on to
    7 min read
  • Maximize the rightmost element of an array in k operations in Linear Time
    Given an array arr[ ] of size N and an integer p, the task is to find maximum possible value of rightmost element of array arr[ ] performing at most k operations.In one operation decrease arr[i] by p and increase arr[i+1] by p. Examples: Input: N = 4, p = 2, k = 5, arr = {3, 8, 1, 4}Output: 8Explana
    9 min read
  • How to Find the Maximum Element in a List in C++?
    In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows us to store data in non-contiguous memory locations efficiently. In this article, we will learn how to find the maximum element in a list in C++. Example: Input: myList = {30, 20, 10, 5
    2 min read
  • C++ Program for Sorting all array elements except one
    Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
    3 min read
  • C++ Program to Maximize elements using another array
    Given two arrays with size n, maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first array). The order of appeara
    4 min read
  • How to Find the Maximum Element in a Deque in C++?
    in C++, double-ended queues, also known as deques, are sequence containers with the feature of insertion and deletion on both ends. They are similar to vectors but are more efficient for the insertion and deletion of elements from both ends. In this article, we will learn how to find the maximum ele
    2 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