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

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of n elements. Our task is to find k maximum elements of the array in original order. 

We need to find k maximum elements of the array and then print then as they were indexed originally.

Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 3, 6, 2}, k  = 2

Output: 5, 6

Explanation: 

The largest two elements of the array are 6 and 5. But 5 comes before 6 in the original array hence we have printed in that way.

Solution Approach

To solve the problem, and print k elements in the original order.

For this we will create a decArray that will store the elements of arr[] in descending order. Then we will traverse the original array and print k largest element in order using the decArray[].

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

bool seachVal(int decArr[], int k, int ele){

   for(int i = 0; i < k; i++){
      if( decArr[i] == ele)
         return true;
   }
   return false;
}

void printKMaxEle(int arr[], int k, int n) {
   
   int decArr[n];
   for(int i = 0; i < n ; i++){
      decArr[i] = arr[i];
   }
   sort(decArr, decArr + n, greater<int>());

   for (int i = 0; i < n; ++i)
      if ( seachVal(decArr, k, arr[i]) )
         cout<<arr[i]<<" ";
}

int main() {
   
   int arr[] = { 15, 1, 3, 6, 2, 34, 8, 9 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 3;
   cout<<k<<" maximum elements of the array in their original order are \n";
   printKMaxEle(arr, k, n);
   return 0;
}

Output

3 maximum elements of the array in their original order are
15 34 9
raja
Published on 25-Jan-2021 04:48:54
Advertisements