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


In this problem, we are given an array arr. Our task is to create a program to find the Maximum value K such that the array has at-least K elements that are >= K in C++.

Problem Description

We need to find a value K, that fulfills the condition that there are K or more elements in the array that are greater than or equal to K.

Let’s take an example to understand the problem,

Input:arr[] = {3, 5, 1, 7, 6, 6, 4, 8}

Output:5

Explanation

Elements in the array that are greater than or equal to 5: 5, 6, 6, 7, 8.

Solution Approach

A simple and effective solution to the problem is by sorting the array and checking from the last index whether the number of elements after the element is greater than the element itself. If yes, return the element.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int CalcMaximumVal(int arr[], int N){
   sort(arr, arr + N);
   for(int i = (N - 1); i >= 0; i--){
      if(arr[i] <= (N - i) )
         return arr[i];
   }
}
int main(){
   int arr[] = {4,7,2,3,8};
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum value K such that array has at-least K elements that are >= K is "<<CalcMaximumVal(arr, N);
   return 0;
}

Output

The maximum value K such that array has at-least K elements that are >= K
is 3

Updated on: 09-Oct-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements