Longest substring with count of 1 s more than 0 s | C # program to find largest substring having count of 1 s more than count count of 0 s . ; Function to find longest substring having count of 1 s more than count of 0 s . ; To store sum . ; To store first occurrence of each sum value . ; To store maximum length . ; To store current substring length . ; Add 1 if current character is 1 else subtract 1. ; If sum is positive , then maximum length substring is bin [ 0. . i ] ; If sum is negative , then maximum length substring is bin [ j + 1. . i ] , where sum of substring bin [ 0. . j ] is sum - 1. ; Make entry for this sum value in hash table if this value is not present . ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int findLongestSub ( String bin ) { int n = bin . Length , i ; int sum = 0 ; Dictionary < int , int > prevSum = new Dictionary < int , int > ( ) ; int maxlen = 0 ; int currlen ; for ( i = 0 ; i < n ; i ++ ) { if ( bin [ i ] == '1' ) sum ++ ; else sum -- ; if ( sum > 0 ) { maxlen = i + 1 ; } else if ( sum <= 0 ) { if ( prevSum . ContainsKey ( sum - 1 ) ) { currlen = i - ( prevSum [ sum - 1 ] == 0 ? 1 : prevSum [ sum - 1 ] ) ; maxlen = Math . Max ( maxlen , currlen ) ; } } if ( ! prevSum . ContainsKey ( sum ) ) prevSum . Add ( sum , i ) ; } return maxlen ; } public static void Main ( String [ ] args ) { String bin = "1010" ; Console . WriteLine ( findLongestSub ( bin ) ) ; } }