Longest substring with count of 1 s more than 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
function findLongestSub ( bin ) { let n = bin . length , i ; let sum = 0 ; let prevSum = new Map ( ) ; let maxlen = 0 ; let currlen ; for ( i = 0 ; i < n ; i ++ ) { if ( bin [ i ] == ' ' ) sum ++ ; else sum -- ; if ( sum > 0 ) { maxlen = i + 1 ; } else if ( sum <= 0 ) { if ( prevSum . has ( sum - 1 ) ) { currlen = i - ( prevSum . get ( sum - 1 ) == null ? 1 : prevSum . get ( sum - 1 ) ) ; maxlen = Math . max ( maxlen , currlen ) ; } } if ( ! prevSum . has ( sum ) ) prevSum . set ( sum , i ) ; } return maxlen ; } let bin = " " ; document . write ( findLongestSub ( bin ) ) ;