Header Ads Widget

Max Mex | codechef solution

Chef has a sequence of positive integers 1,2,,. He wants to choose some elements of this sequence (possibly none or all of them) and compute their MEX, i.e. the smallest positive integer which does not occur among the chosen elements. For example, the MEX of [1,2,4] is 3.

Help Chef find the largest number of elements of the sequence  which he can choose such that their MEX is equal to , or determine that it is impossible.

Input

  • The first line of the input contains a single integer  denoting the number of test cases. The description of  test cases follows.
  • The first line of each test case contains two space-separated integers  and .
  • The second line contains  space-separated integers 1,2,,.

Output

For each test case, print a single line containing one integer ― the maximum number of elements Chef can choose, or 1 if he cannot choose elements in such a way that their MEX is .

Constraints

  • 1100
  • 2105
  • 1109 for each valid 
  • the sum of  over all test cases does not exceed 106

Sample 1:

Input
Output
1
3 3
1 2 4
3

Explanation:

Example case 1: The MEX of whole array is 3. Hence, we can choose all the elements. 

Code(C++):-

#include<bits/stdc++.h>
using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;
int a[n];
int cnt=0;
        for(int i=0;i<n;i++)
        {
cin>>a[i];
if(a[i]==m)
 cnt++;
        }
        sort(a,a+n);
int temp=1;
bool flag=1;
for(int i=0;i<n && temp<m;i++)
{
if(temp<a[i])
{
   flag=0;
   break;
}
if(temp==a[i])
temp++;
}

     if(flag==1 && temp==m)
       cout<<n-cnt<<"\n";
     else
       cout<<"-1\n";
    }
}

Code(JAVA):-

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(br.readLine()),n,m,x;
        while(t-->0)
        {
         String s[]= br.readLine().split(" ");
         n=Integer.parseInt(s[0]);
         m=Integer.parseInt(s[1]);
         s= br.readLine().split(" ");
         int a[]=new int[m];
         for(String c:s)
         {
         x=Integer.parseInt(c);
         if(x<=m)
         a[x-1]++;
         }
         x=0;
         for(int i=0;i<m-1;i++)
         if(a[i]<1)
         {
         x=1;
         break;
         }
         if(x==1)
         System.out.println(-1);
         else
         System.out.println(n-a[m-1]);
        }
    }
}

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-