Number of NGEs to the right in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that count the number os NGEs to the right of the given indexed element.

You are given an array and the index of the target element. We have to count the number of elements greater than the given element to its right.

Let's see the steps to solve the problem.

  • Initialise the array and index of target element.

  • Write a loop that iterates from the next element of the given index.

    • Increment the count if the element is greater than the target element.

  • Return the count.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getNextGreaterElementsCount(int arr[], int n, int index) {
   if (index >= n) {
      return -1;
   }
   int count = 0;
   for (int i = index + 1; i < n; i++) {
      if (arr[index] < arr[i]) {
         count += 1;
      }
   }
   return count;
}
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
   int n = 8, index = 1;
   cout << getNextGreaterElementsCount(arr, n, index) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

6

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 08:16:54
Advertisements