Maximum value K such that array has at-least K elements that are >= K in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum value K such that array has at-least K elements that are >= K.

For this we will be provided with an array containing positive values. Our task is to find the value of K such that the array contains atleast K values greater than or equal to K.

Example

 Live Demo

#include <iostream>
using namespace std;
//calculating maximum value of K
int findMaximumNum(unsigned int arr[], int n) {
   for (int i = n; i >= 1; i--) {
      int count = 0;
      for (int j=0; j<n; j++)
         if (i <= arr[j])
            count++;
         if (count >= i)
            return i;
   }
   return 1;
}
int main() {
   unsigned int arr[] = {1, 2, 3, 8, 10 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << findMaximumNum(arr, n);
   return 0;
}

Output

3
raja
Published on 27-Jul-2020 12:06:04
Advertisements