Largest subset with M as smallest missing number | Java program to implement the above approach ; Function to find and return the length of the longest subset whose smallest missing value is M ; Initialize a set ; If array element is not equal to M ; Insert into set ; Increment frequency ; Stores minimum missing number ; Iterate to find the minimum missing integer ; If minimum obtained is less than M ; Update answer ; Return answer ; Driver code
import java . util . * ; class GFG { static int findLengthOfMaxSubset ( int arr [ ] , int n , int m ) { Set < Integer > s = new HashSet < > ( ) ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int tmp = arr [ i ] ; if ( tmp != m ) { s . add ( tmp ) ; answer ++ ; } } int min = 1 ; while ( s . contains ( min ) ) { min ++ ; } if ( min != m ) { answer = - 1 ; } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 } ; int N = arr . length ; int M = 3 ; System . out . print ( findLengthOfMaxSubset ( arr , N , M ) ) ; } }