Given an array arr of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array. If there is no lucky integer return -1.


Input Format

N as size

N int value as array elements


Constraints

1<=N<=10^5

1<=arr[i]<10


Output Format

Lucky Number


Sample Input 0

5

1 2 2 3 4


Sample Output 0

2


Explanation 0

There are two lucky numbers:

1 because frequency of 1 is equals to 1

2 because frequency of 2 is equals to 2.

2 is largest among the two lucky numbers, hence output is 2.

CLICK HERE TO BROWSE MORE CODES

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static int findLucky(int[] arr) {
       int freq=0;
       int n=arr.length;
        for(int i=n-1; i>=0; i--){
            freq++;
            if(i==0 || arr[i]!=arr[i-1]){
                if(freq==arr[i]){
                    return freq;
                }
                freq=0;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
         int n=sc.nextInt();
        int[] arr=new int[n];
        for(int i=0; i< n; i++){
            arr[i]=sc.nextInt();
        }
        int ans=findLucky(arr); 
        System.out.println(ans);
   }
}
teckforest.blog