Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize count of array elements to be removed such that at least K elements are equal to their index values
Next article icon

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

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of positive integers, find maximum possible value K such that the array has at-least K elements that are greater than or equal to K. The array is unsorted and may contain duplicate values.

Examples : 

Input: [2, 3, 4, 5, 6, 7] Output: 4 Explanation : 4 elements [4, 5, 6, 7]              are greater than equal to 4  Input: [1, 2, 3, 4] Output: 2 Explanation : 3 elements [2, 3, 4] are                 greater than equal to 2  Input: [4, 7, 2, 3, 8] Output: 3  Explanation : 4 elements [4, 7, 3, 8]            are greater than equal to 3    Input: [6, 7, 9, 8, 10] Output: 5 Explanation : All 5 elements are greater               than equal to 5 

Expected time complexity : O(n)

Recommended Practice
Maximum value K
Try It!

Method 1 [Simple : O(n2) time] :

Let size of input array be n. Let us consider following important observations.

  1. The maximum possible value of result can be n. We get the maximum possible value when all elements are greater than or equal to n. For example, if input array is {10, 20, 30}, n is 3. The value of result can’t be greater than 3.
  2. The minimum possible value would be 1. An example case when get this output is, when all elements are 1.

So we can run a loop from n to 1 and count greater elements for every value. 

C++




// C++ program to find maximum possible value K
// such that array has at-least K elements that
// are greater than or equals to K.
#include <iostream>
using namespace std;
 
// Function to return maximum possible value K
// such that array has atleast K elements that
// are greater than or equals to K
int findMaximumNum(unsigned int arr[], int n)
{
    // output can contain any number from n to 0
    // where n is length of the array
 
    // We start a loop from n as we need to find
    // maximum possible value
    for (int i = n; i >= 1; i--)
    {
        // count contains total number of elements
        // in input array that are more than equal to i
        int count = 0;
 
        // traverse the input array and find count
        for (int j=0; j<n; j++)
            if (i <= arr[j])
                count++;
 
        if (count >= i)
          return i;
    }   
    return 1;
}
 
// Driver code
int main()
{
    unsigned int arr[] = {1, 2, 3, 8, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findMaximumNum(arr, n);
    return 0;
}
 
 

Java




// Java program to find maximum
// possible value K such that
// array has at-least K elements
// that are greater than or equals to K.
import java.io.*;
 
class GFG
{
 
// Function to return maximum
// possible value K such that
// array has atleast K elements
// that are greater than or equals to K
static int findMaximumNum(int arr[],
                          int n)
{
    // output can contain any
    // number from n to 0 where
    // n is length of the array
 
    // We start a loop from n
    // as we need to find
    // maximum possible value
    for (int i = n; i >= 1; i--)
    {
        // count contains total
        // number of elements
        // in input array that
        // are more than equal to i
        int count = 0;
 
        // traverse the input
        // array and find count
        for (int j = 0; j < n; j++)
            if (i <= arr[j])
                count++;
 
        if (count >= i)
        return i;
    }
    return 1;
}
 
// Driver code
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 8, 10 };
int n = arr.length;
System.out.println(findMaximumNum(arr, n));
}
}
 
// This code is contributed by aj_36
 
 

Python3




# python 3 program to find maximum possible value K
# such that array has at-least K elements that
# are greater than or equals to K.
 
# Function to return maximum possible value K
# such that array has atleast K elements that
# are greater than or equals to K
def findMaximumNum(arr, n):
    # output can contain any number from n to 0
    # where n is length of the array
 
    # We start a loop from n as we need to find
    # maximum possible value
    i = n
    while(i >= 1):
        # count contains total number of elements
        # in input array that are more than equal to i
        count = 0
 
        # traverse the input array and find count
        for j in range(0,n,1):
            if (i <= arr[j]):
                count += 1
 
        if (count >= i):
            return i
             
        i -= 1
     
    return 1
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 8, 10]
    n = len(arr)
    print(findMaximumNum(arr, n))
 
# This code is contributed by
# Surendra_Gangwar
 
 

C#




// C# program to find maximum
// possible value K such that
// array has at-least K elements
// that are greater than or equals to K.
using System;
 
class GFG
{
     
// Function to return maximum
// possible value K such that
// array has atleast K elements
// that are greater than or equals to K
static int findMaximumNum(int []arr,
                          int n)
{
    // output can contain any
    // number from n to 0 where
    // n is length of the array
 
    // We start a loop from n
    // as we need to find
    // maximum possible value
    for (int i = n; i >= 1; i--)
    {
        // count contains total
        // number of elements
        // in input array that
        // are more than equal to i
        int count = 0;
 
        // traverse the input
        // array and find count
        for (int j = 0; j < n; j++)
            if (i <= arr[j])
                count++;
 
        if (count >= i)
        return i;
    }
    return 1;
}
 
// Driver code
static public void Main ()
{
    int []arr = {1, 2, 3, 8, 10 };
    int n = arr.Length;
    Console.WriteLine(findMaximumNum(arr, n));
}
}
 
// This code is contributed by m_kit
 
 

PHP




<?php
// PHP program to find maximum
// possible value K such that
// array has at-least K elements
// that are greater than or
// equals to K.
 
// Function to return maximum
// possible value K such that
// array has atleast K elements
// that are greater than or
// equals to K
function findMaximumNum($arr, $n)
{
    // output can contain any
    // number from n to 0 where
    // n is length of the array
 
    // We start a loop from
    // n as we need to find
    // maximum possible value
    for ($i = $n; $i >= 1; $i--)
    {
        // count contains total
        // number of elements in
        // input array that are
        // more than equal to i
        $count = 0;
 
        // traverse the input
        // array and find count
        for ($j = 0; $j < $n; $j++)
            if ($i <= $arr[$j])
                $count++;
 
        if ($count >= $i)
        return $i;
    }
    return 1;
}
 
// Driver code
$arr = array (1, 2, 3, 8, 10);
$n = sizeof($arr);
echo findMaximumNum($arr, $n);
 
// This code is contributed by ajit
?>
 
 

Javascript




<script>
 
    // Javascript program to find maximum
    // possible value K such that
    // array has at-least K elements
    // that are greater than or equals to K.
     
    // Function to return maximum
    // possible value K such that
    // array has atleast K elements
    // that are greater than or equals to K
    function findMaximumNum(arr, n)
    {
        // output can contain any
        // number from n to 0 where
        // n is length of the array
 
        // We start a loop from n
        // as we need to find
        // maximum possible value
        for (let i = n; i >= 1; i--)
        {
            // count contains total
            // number of elements
            // in input array that
            // are more than equal to i
            let count = 0;
 
            // traverse the input
            // array and find count
            for (let j = 0; j < n; j++)
                if (i <= arr[j])
                    count++;
 
            if (count >= i)
            return i;
        }
        return 1;
    }
     
    let arr = [1, 2, 3, 8, 10 ];
    let n = arr.length;
    document.write(findMaximumNum(arr, n));
     
</script>
 
 
Output
3

Time Complexity : O(N2) ,here N is size of array.

Space Complexity : O(1)  ,since no  extra space required.

Method 2 [Efficient : O(n) time and O(n) extra space] 

  1. The idea is to construct auxiliary array of size n + 1, and use that array to find count of greater elements in input array. Let the auxiliary array be freq[]. We initialize all elements of this array as 0.
  2. We process all input elements. 
    1. If an element arr[i] is less than n, then we increment its frequency, i.e., we do freq[arr[i]]++. 
    2. Else we increment freq[n].
  3. After step 2 we have two things. 
    1. Frequencies of elements for elements smaller than n stored in freq[0..n-1]. 
    2. Count of elements greater than n stored in freq[n].

Finally, we process the freq[] array backwards to find the output by keeping sum of the values processed so far.

Below is implementation of above idea.

C++




// C++ program to find maximum possible value K such
// that array has atleast K elements that are greater
// than or equals to K.
#include <bits/stdc++.h>
using namespace std;
 
// Function to return maximum possible value K such
// that array has at-least K elements that are greater
// than or equals to K.
int findMaximumNum(unsigned int arr[], int n)
{
    // construct auxiliary array of size n + 1 and
    // initialize the array with 0
    vector<int> freq(n+1, 0);
 
    // store the frequency of elements of
    // input array in the auxiliary array
    for (int i = 0; i < n; i++)
    {
        // If element is smaller than n, update its
        // frequency
        if (arr[i] < n)
            freq[arr[i]]++;
 
        // Else increment count of elements greater
        // than n.
        else
            freq[n]++;
    }
 
    // sum stores number of elements in input array
    // that are greater than or equal to current
    // index
    int sum = 0;
 
    // scan auxiliary array backwards
    for (int i = n; i > 0; i--)
    {
        sum += freq[i];
 
        // if sum is greater than current index,
        // current index is the answer
        if (sum >= i)
            return i;
    }
}
 
// Driver code
int main()
{
    unsigned int arr[] = {1, 2, 3, 8, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << findMaximumNum(arr, n);
 
    return 0;
}
 
 

Java




// Java program to find maximum possible value K such
// that array has atleast K elements that are greater
// than or equals to K.
 
import java.util.Vector;
 
class GFG {
 
// Function to return maximum possible value K such
// that array has at-least K elements that are greater
// than or equals to K.
    static int findMaximumNum(int arr[], int n) {
        // construct auxiliary array of size n + 1 and
        // initialize the array with 0
        int[] freq=new int[n+1];
        for (int i = 0; i < n + 1; i++) {
            freq[i] = 0;
        }
 
        // store the frequency of elements of
        // input array in the auxiliary array
        for (int i = 0; i < n; i++) {
            // If element is smaller than n, update its
            // frequency
            if (arr[i] < n) //
            {
                freq[arr[i]]++;
            } // Else increment count of elements greater
            // than n.
            else {
                freq[n]++;
            }
        }
 
        // sum stores number of elements in input array
        // that are greater than or equal to current
        // index
        int sum = 0;
 
        // scan auxiliary array backwards
        for (int i = n; i > 0; i--) {
            sum += freq[i];
 
            // if sum is greater than current index,
            // current index is the answer
            if (sum >= i) {
                return i;
            }
        }
        return 0;
    }
 
// Driver code
    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 8, 10};
        int n = arr.length;
        System.out.println(findMaximumNum(arr, n));
    }
}
/*This Java code is contributed by koulick_sadhu*/
 
 

Python3




# Python program to find maximum possible value K such
# that array has atleast K elements that are greater
# than or equals to K.
 
# Function to return maximum possible value K such
# that array has at-least K elements that are greater
# than or equals to K.
def findMaximumNum(arr, n):
 
    # construct auxiliary array of size n + 1 and
    # initialize the array with 0
    freq = [0 for i in range(n+1)]
 
    # store the frequency of elements of
    # input array in the auxiliary array
    for i in range(n):
        # If element is smaller than n, update its
        # frequency
        if (arr[i] < n):
            freq[arr[i]] += 1
 
        # Else increment count of elements greater
        # than n.
        else:
            freq[n] += 1
 
    # sum stores number of elements in input array
    # that are greater than or equal to current
    # index
    sum = 0
 
    # scan auxiliary array backwards
    for i in range(n,0,-1):
        sum += freq[i]
 
        # if sum is greater than current index,
        # current index is the answer
        if (sum >= i):
            return i
 
# Driver code
arr = [1, 2, 3, 8, 10]
n = len(arr)
print(findMaximumNum(arr, n))
 
# This code is contributed by shinjanpatra
 
 

C#




// C# program to find maximum possible value K such
// that array has atleast K elements that are greater
// than or equals to K.
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to return maximum possible value K such
    // that array has at-least K elements that are greater
    // than or equals to K.
    static int findMaximumNum(int []arr, int n)
    {
        // construct auxiliary array of size n + 1 and
        // initialize the array with 0
        List<int> freq = new List<int>();
        for (int i = 0; i < n + 1; i++)
        {
            freq.Insert(i, 0);
        }
 
        // store the frequency of elements of
        // input array in the auxiliary array
        for (int i = 0; i < n; i++)
        {
            // If element is smaller than n, update its
            // frequency
            if (arr[i] < n) //freq[arr[i]]++;
            {
                freq.Insert(arr[i], freq[arr[i]] + 1);
            }
            // Else increment count of elements greater
            // than n.
            else
            {
                freq.Insert(n, freq[n] + 1);
            }
            //freq[n]++;
        }
 
        // sum stores number of elements in input array
        // that are greater than or equal to current
        // index
        int sum = 0;
 
        // scan auxiliary array backwards
        for (int i = n; i > 0; i--)
        {
            sum += freq[i];
 
            // if sum is greater than current index,
            // current index is the answer
            if (sum >= i)
            {
                return i;
            }
        }
        return 0;
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = {1, 2, 3, 8, 10};
        int n = arr.Length;
        Console.WriteLine(findMaximumNum(arr, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */
 
 

Javascript




<script>
// Javascript program to find maximum possible value K such
// that array has atleast K elements that are greater
// than or equals to K.
 
// Function to return maximum possible value K such
// that array has at-least K elements that are greater
// than or equals to K.
function findMaximumNum(arr, n)
{
 
    // construct auxiliary array of size n + 1 and
    // initialize the array with 0
    let freq = new Array(n + 1).fill(0);
 
    // store the frequency of elements of
    // input array in the auxiliary array
    for (let i = 0; i < n; i++) {
        // If element is smaller than n, update its
        // frequency
        if (arr[i] < n)
            freq[arr[i]]++;
 
        // Else increment count of elements greater
        // than n.
        else
            freq[n]++;
    }
 
    // sum stores number of elements in input array
    // that are greater than or equal to current
    // index
    let sum = 0;
 
    // scan auxiliary array backwards
    for (let i = n; i > 0; i--) {
        sum += freq[i];
 
        // if sum is greater than current index,
        // current index is the answer
        if (sum >= i)
            return i;
    }
}
 
// Driver code
let arr = [1, 2, 3, 8, 10];
let n = arr.length;
document.write(findMaximumNum(arr, n));
 
// This code is contributed by gfgking.
</script>
 
 
Output
3


Next Article
Minimize count of array elements to be removed such that at least K elements are equal to their index values

A

Aditya Goel
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Find K for every Array element such that at least K prefixes are ≥ K
    Given an array arr[] consisting of N non-negative integers, the task is to find an integer K for every index such that at least K integers in the array till that index are greater or equal to K. Note: Consider 1-based indexing Examples: Input: arr[] = {3, 0, 6, 1, 5} Output: K = {1, 1, 2, 2, 3} Expl
    7 min read
  • Minimize count of array elements to be removed such that at least K elements are equal to their index values
    Given an array arr[](1- based indexing) consisting of N integers and a positive integer K, the task is to find the minimum number of array elements that must be removed such that at least K array elements are equal to their index values. If it is not possible to do so, then print -1. Examples: Input
    13 min read
  • Find X such that most Array elements are of form (X + p*K)
    Given an array arr[] and a number K, the task is to find a value X such that maximum number of array elements can be expressed in the form (X + p*K). Note: If there are multiple possible values of X, print the minimum among them. Examples: Input: arr[] = {1, 3, 5, 2, 4, 6}, k = 2Output: 1Explanation
    11 min read
  • Find a number K such that Array contains at least K numbers greater than or equal to K
    Given an array arr[] of non-negative integers of size N, the task is to find an integer H such that at least K integers in the array are greater or equal to K.Examples: Input: arr[] = [3, 0, 6, 1, 5] Output: 3 Explanation: There are 3 number greater than or equal to 3 in the array i.e. 3, 6 and 5.In
    4 min read
  • Reduce the array such that each element appears at most K times
    Given a sorted array arr of size N, the task is to reduce the array such that each element can appear at most K times.Examples: Input: arr[] = {1, 2, 2, 2, 3}, K = 2 Output: {1, 2, 2, 3} Explanation: Remove 2 once, as it occurs more than 2 times.Input: arr[] = {3, 3, 3}, K = 1 Output: {3} Explanatio
    10 min read
  • Find a number K such that exactly K array elements are greater than or equal to K
    Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1. Examples: Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is le
    10 min read
  • Maximize Kth largest element after splitting the given Array at most C times
    Given an array arr[] and two positive integers K and C, the task is to maximize the Kth maximum element obtained after splitting an array element arr[] into two parts(not necessarily an integer) C number of times. Print -1 if there doesn't exist Kth maximum element. Note: It is compulsory to do spli
    7 min read
  • Maximise K that can be reduced from Array to make all elements equal
    Given an array arr[] of size N, the task is to make all elements equal by applying the operation given below any number of times (possibly zero) to any of the elements in the given array. Select an element in the array.Reduce it by a positive integer K. Among all such positive k's, print the maximum
    6 min read
  • Maximize 0s to be flipped in given Binary array such that there are at least K 0s between two 1s
    Given a binary array arr[] and an integer K, the task is to count the maximum number of 0's that can be flipped to 1's such that there are at least K 0's between two 1's. Example: Input: arr[] = {0, 0, 1, 0, 0, 0}, K = 1Output: 2Explanation: The 1st and the 5th index in the array arr[] can be flippe
    7 min read
  • Smallest subarray such that all elements are greater than K
    Given an array of N integers and a number K, the task is to find the length of the smallest subarray in which all the elements are greater than K. If there is no such subarray possible, then print -1. Examples: Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5 Output: 1 The subarray is {10} Input: a[]
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences