Length of longest subset consisting of A 0 s and B 1 s from an array of strings | Java program for the above approach ; Function to count 0 's in a string ; Stores count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive function to find the length of longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; If idx is equal to N or A + B is equal to 0 ; Stores the count of 0 's in arr[idx] ; Stores the count of 1 's in arr[idx] ; Stores the length of the subset if arr [ i ] is included ; If zero is less than or equal to A and one is less than or equal to B ; Stores the length of the subset if arr [ i ] is excluded ; Returns max of inc and exc ; Function to find the length of the longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; Return ;
import java . util . * ; class GFG { static int count0 ( String s ) { int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { count ++ ; } } return count ; } static int solve ( String [ ] vec , int A , int B , int idx ) { if ( idx == vec . length A + B == 0 ) { return 0 ; } int zero = count0 ( vec [ idx ] ) ; int one = vec [ idx ] . length ( ) - zero ; int inc = 0 ; if ( zero <= A && one <= B ) { inc = 1 + solve ( vec , A - zero , B - one , idx + 1 ) ; } int exc = solve ( vec , A , B , idx + 1 ) ; return Math . max ( inc , exc ) ; } static int MaxSubsetlength ( String [ ] arr , int A , int B ) { return solve ( arr , A , B , 0 ) ; } public static void main ( String [ ] args ) { String [ ] arr = { "1" , "0" , "10" } ; int A = 1 , B = 1 ; System . out . print ( MaxSubsetlength ( arr , A , B ) ) ; } }