Longest subarray having count of 1 s one more than count of 0 s | function to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as ' - 1' ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver program to test above
function lenOfLongSubarr ( arr , n ) { var um = new Map ( ) ; var sum = 0 , maxLen = 0 ; for ( var i = 0 ; i < n ; i ++ ) { sum += arr [ i ] == 0 ? - 1 : 1 ; if ( sum == 1 ) maxLen = i + 1 ; else if ( ! um . has ( sum ) ) um . set ( sum , i ) ; if ( um . has ( sum - 1 ) ) { if ( maxLen < ( i - um . get ( sum - 1 ) ) ) maxLen = i - um . get ( sum - 1 ) ; } } return maxLen ; } var arr = [ 0 , 1 , 1 , 0 , 0 , 1 ] ; var n = arr . length ; document . write ( " " + lenOfLongSubarr ( arr , n ) ) ;