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:
Maximum number of elements that can be removed such that MEX of the given array remains unchanged
Next article icon

Count the maximum number of elements that can be selected from the array

Last Updated : 14 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to count the maximum number of elements that can be selected from the given array following the below selection process: 

  • At 1st selection, select an element which is greater than or equal to 1.
  • At 2nd selection, select an element which is greater than or equal to 2.
  • At 3rd selection, select an element which is greater than or equal to 3 and so on.


An element can be selected only once. The operation stops when it is not possible to select any element. So, the task is to maximize the count of selection from the array.

Examples: 

Input : arr[] = { 4, 1, 3, 1 } 
Output : 3 
1st Selection: 1 is selected as 1 >= 1. 
2nd Selection: 3 is selected as 3 >= 2. 
3rd Selection: 4 is selected as 4 >= 3. 
No more selections are possible. Therefore, the answers is 3. 

Input : arr[] = { 2, 1, 1, 2, 1 } 
Output : 2 
 

Approach: In order to maximize the count of selection it is necessary to select the smallest possible numbers first and then the bigger numbers if the selection is not possible. This can be done easily by sorting the array. Now, loop through the array and increment the result by 1 when the element is greater than or equal to the number to select for the current operation.

Below is the implementation of the above approach:  

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Function to return the maximum count of  // selection possible from the given array  // following the given process int maxSelectionCount(int a[], int n) {     // Initialize result     int res = 0;      // Sorting the array     sort(a, a + n);      // Initialize the select variable     int select = 1;      // Loop through array     for (int i = 0; i < n; i++) {         // If selection is possible         if (a[i] >= select) {             res++; // Increment result             select++; // Increment selection variable         }     }      return res; }  // Driver Code int main() {     int arr[] = { 4, 2, 1, 3, 5, 1, 4 };      int N = sizeof(arr) / sizeof(arr[0]);      cout << maxSelectionCount(arr, N);      return 0; } 
Java
// Java implementation of the approach import java.util.*;  class GFG  {      // Function to return the maximum count of      // selection possible from the given array      // following the given process     static int maxSelectionCount(int a[], int n)      {         // Initialize result         int res = 0;          // Sorting the array         Arrays.sort(a);          // Initialize the select variable         int select = 1;          // Loop through array         for (int i = 0; i < n; i++)         {             // If selection is possible             if (a[i] >= select)              {                 res++; // Increment result                 select++; // Increment selection variable             }         }          return res;     }      // Driver Code     public static void main(String[] args)     {         int arr[] = {4, 2, 1, 3, 5, 1, 4};          int N = arr.length;          System.out.println(maxSelectionCount(arr, N));     } }  // This code contributed by Rajput-Ji 
Python3
# Python implementation of the approach  # Function to return the maximum count of  # selection possible from the given array  # following the given process def maxSelectionCount(a, n):     # Initialize result     res = 0;      # Sorting the array     a.sort();      # Initialize the select variable     select = 1;      # Loop through array     for i in range(n):         # If selection is possible         if (a[i] >= select):             res += 1; # Increment result             select += 1; # Increment selection variable      return res;   # Driver Code arr = [ 4, 2, 1, 3, 5, 1, 4 ]; N = len(arr); print(maxSelectionCount(arr, N));  # This code contributed by PrinciRaj1992 
C#
// C# implementation of the approach  using System;  class GFG  {      // Function to return the maximum count of      // selection possible from the given array      // following the given process      static int maxSelectionCount(int []a, int n)      {          // Initialize result          int res = 0;           // Sorting the array          Array.Sort(a);           // Initialize the select variable          int select = 1;           // Loop through array          for (int i = 0; i < n; i++)          {              // If selection is possible              if (a[i] >= select)              {                  res++; // Increment result                  select++; // Increment selection variable              }          }           return res;      }       // Driver Code      public static void Main()      {          int []arr = {4, 2, 1, 3, 5, 1, 4};           int N = arr.Length;           Console.WriteLine(maxSelectionCount(arr, N));      }  }   // This code contributed by AnkitRai01 
JavaScript
<script>  // Javascript implementation of the approach  // Function to return the maximum count of  // selection possible from the given array  // following the given process function maxSelectionCount(a, n) {          // Initialize result     var res = 0;      // Sorting the array     a.sort();      // Initialize the select variable     var select = 1;      // Loop through array     for(var i = 0; i < n; i++)      {                  // If selection is possible         if (a[i] >= select)         {             // Increment result             res++;                           // Increment selection variable             select++;          }     }     return res; }  // Driver Code var arr = [ 4, 2, 1, 3, 5, 1, 4 ]; var N = arr.length;  document.write(maxSelectionCount(arr, N));  // This code is contributed by rrrtnx  </script> 

Output: 
5

 

Time Complexity: O(N * log(N))
Auxiliary Space: O(1) 
 


Next Article
Maximum number of elements that can be removed such that MEX of the given array remains unchanged
author
rupesh_rao
Improve
Article Tags :
  • Sorting
  • Competitive Programming
  • Data Structures
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Data Structures
  • Sorting

Similar Reads

  • Maximize count of K unique elements that can be chosen from Array
    Given an arrays arr[] of size N and an array of queries Q[] of size M, where Q[i] defines the count of unique elements that have to be chosen from the array arr[]. The task to find the maximum number of elements that can be picked for each query. Examples: Input: arr[ ] = {30, 31, 32, 33, 32, 32, 31
    6 min read
  • Number of ways to choose elements from the array such that their average is K
    Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. Examples: Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8,
    11 min read
  • Maximum number of elements that can be removed such that MEX of the given array remains unchanged
    Given an array arr[] of size N, the task is to count the maximum number of elements that can be removed from the given array without changing the MEX of the original array. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {2, 3, 5, 1, 6} Output: 2 E
    6 min read
  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Maximize sum of selected numbers from Array to empty it | Set 2
    Given an array arr[] of N integers, the task is to maximize the sum of selected numbers over all the operations such that in each operation, choose a number Ai, delete one occurrence of it and delete all occurrences of Ai - 1 and Ai + 1 (if they exist) in the array until the array gets empty. Exampl
    7 min read
  • Count of ways to choose K elements from given Array with maximum sum
    Given an array, arr[] of size N and an integer K, the task is to find the number of ways of selecting K array elements, such that the sum of these K elements is the maximum possible sum. Examples: Input: arr[] = {3, 1, 1, 2}, K = 3 Output: 2Explanation: The possible ways of selecting 3 elements are:
    8 min read
  • Max count of items that can be removed from the Array without changing the mode
    Given an array arr[] of N integers, the goal is to find the maximum count of items that can be removed from the array without changing the mode. You can remove any number of occurrences of items of the same value let's say K at one step. Now, for removing the next value i.e., different from K, the a
    7 min read
  • Count subsequences which contains both the maximum and minimum array element
    Given an array arr[] consisting of N integers, the task is to find the number of subsequences which contain the maximum as well as the minimum element present in the given array. Example : Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: There are 4 subsequence {1, 4}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3
    6 min read
  • Maximize the sum of selected numbers from an array to make it empty
    Given an array A[] of N numbers, we need to maximize the sum of selected numbers following the given operation: At each step, you need to select a number Ai, delete one occurrence and add it to the sum.Delete one occurrence of Ai-1 and Ai+1 (if they exist in the array). Repeat these steps until the
    15+ min read
  • Maximum sum such that exactly half of the elements are selected and no two adjacent
    Given an array A containing N integers. Find the maximum sum possible such that exact floor(N/2) elements are selected and no two selected elements are adjacent to each other. (if N = 5, then exactly 2 elements should be selected as floor(5/2) = 2) For a simpler version of this problem check out thi
    14 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