Maximum difference of zeros and ones in binary string | C # 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
using System ; class GFG { static int MAX = 100 ; public static bool allones ( string s , int n ) { int co = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) co += ( s [ i ] == '1' ? 1 : 0 ) ; return ( co == n ) ; } public static int findlength ( int [ ] arr , string s , int n , int ind , int st , int [ , ] 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 ) ; } public static int maxLen ( string s , int n ) { if ( allones ( s , n ) ) return - 1 ; int [ ] arr = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = ( s [ i ] == '0' ? 1 : - 1 ) ; int [ , ] dp = new int [ MAX , 3 ] ; for ( int i = 0 ; i < MAX ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) dp [ i , j ] = - 1 ; return findlength ( arr , s , n , 0 , 0 , dp ) ; } static void Main ( ) { string s = "11000010001" ; int n = 11 ; Console . Write ( maxLen ( s , n ) ) ; } }