Maximum difference of zeros and ones in binary string | Javascript Program to find the length of substring with maximum difference of zeroes and ones in binary string . ; Return true if there all 1 s ; Checking each index is 0 or not . ; Find the length of substring with maximum difference of zeroes and ones in binary string ; If string is over . ; If the state is already calculated . ; Returns length of substring which is having maximum difference of number of 0 s and number of 1 s ; If all 1 s return - 1. ; Else find the length . ; Driven Program
var MAX = 100 ; function allones ( s , n ) { var co = 0 ; for ( var i = 0 ; i < s . length ; i ++ ) co += ( s [ i ] == ' ' ) ; return ( co == n ) ; } function findlength ( arr , s , n , ind , st , dp ) { if ( ind >= n ) return 0 ; if ( dp [ ind ] [ st ] != - 1 ) return dp [ ind ] [ st ] ; if ( st == 0 ) return dp [ ind ] [ st ] = Math . max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , findlength ( arr , s , n , ind + 1 , 0 , dp ) ) ; else return dp [ ind ] [ st ] = Math . max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , 0 ) ; } function maxLen ( s , n ) { if ( allones ( s , n ) ) return - 1 ; var arr = Array ( MAX ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) arr [ i ] = ( s [ i ] == ' ' ? 1 : - 1 ) ; var dp = Array . from ( Array ( MAX ) , ( ) => Array ( 3 ) . fill ( - 1 ) ) ; return findlength ( arr , s , n , 0 , 0 , dp ) ; } var s = " " ; var n = 11 ; document . write ( maxLen ( s , n ) ) ;