text: Length of longest subset consisting of A 0 s and B 1 s from an array of strings | Set 2 | Java program for the above approach ; Function to find the length of the longest subset of an array of strings with at most A 0 s and B 1 s ; Initialize a 2D array with its entries as 0 ; Traverse the given array ; Store the count of 0 s and 1 s in the current string ; Iterate in the range [ A , zeros ] ; Iterate in the range [ B , ones ] ; Update the value of dp [ i ] [ j ] ; Print the result ; Driver Code
code: import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int MaxSubsetlength ( String arr [ ] , int A , int B ) { int dp [ ] [ ] = new int [ A + 1 ] [ B + 1 ] ; for ( String str : arr ) { int zeros = 0 , ones = 0 ; for ( char ch : str . toCharArray ( ) ) { if ( ch == '0' ) zeros ++ ; else ones ++ ; } for ( int i = A ; i >= zeros ; i -- ) for ( int j = B ; j >= ones ; j -- ) dp [ i ] [ j ] = Math . max ( dp [ i ] [ j ] , dp [ i - zeros ] [ j - ones ] + 1 ) ; } return dp [ A ] [ B ] ; } public static void main ( String [ ] args ) { String arr [ ] = { "1" , "0" , "0001" , "10" , "111001" } ; int A = 5 , B = 3 ; System . out . println ( MaxSubsetlength ( arr , A , B ) ) ; } }