Find all elements in array which have at-least two greater elements in C++

C++Server Side ProgrammingProgramming

Suppose, we have an array of n numbers. We have to find all elements in array, which have at least two greater elements. If the array is like A = [2, 8, 7, 1, 5], then the result will be [2, 1, 5]

To solve this, we will find second max element, then print all elements which is less than or equal to second max value.

Example

#include<iostream>
using namespace std;
void searchElements(int arr[], int n) {
   int first_max = INT_MIN, second_max = INT_MIN;
   for (int i = 0; i < n; i++) {
      if (arr[i] > first_max) {
         second_max = first_max;
         first_max = arr[i];
      } else if (arr[i] > second_max)
         second_max = arr[i];
   }
   for (int i = 0; i < n; i++)
   if (arr[i] < second_max)
   cout << arr[i] << " ";
}
int main() {
   int arr[] = { 2, 9, 1, 7, 5, 3, 17};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Elements are: ";
   searchElements(arr, n);
}

Output

Elements are: 2 1 7 5 3
raja
Published on 18-Dec-2019 10:28:04
Advertisements