Find a number K such that exactly K array elements are greater than or equal to K | Java program for the above approach ; Function to find K for which there are exactly K array elements greater than or equal to K ; Finding the largest array element ; Possible values of K ; Traverse the array ; If current array element is greater than or equal to i ; If i array elements are greater than or equal to i ; Otherwise ; To find maximum Element ; Driver Code
import java . io . * ; class GFG { public static int zvalue ( int [ ] nums ) { int m = max_element ( nums ) ; int cnt = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { cnt = 0 ; for ( int j = 0 ; j < nums . length ; j ++ ) { if ( nums [ j ] >= i ) cnt ++ ; } if ( cnt == i ) return i ; } return - 1 ; } public static int max_element ( int [ ] nums ) { int max = nums [ 0 ] ; for ( int i = 1 ; i < nums . length ; i ++ ) max = Math . max ( max , nums [ i ] ) ; return max ; } public static void main ( String args [ ] ) { int [ ] nums = { 7 , 8 , 9 , 0 , 0 , 1 } ; System . out . println ( zvalue ( nums ) ) ; } }