Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle | JavaScript program to find the longest subsequence possible that starts and ends with 1 and filled with 0 in the middle ; Prefix array to store the occurences of '1' and '0' ; Iterate over the length of the string ; If current character is '1' ; If current character is '0' ; Add '1' available for the first string ; Add '0' available for the second string ; Add '1' available for the third string ; Update answer ; Print the readonly result ; Driver code
function longestSubseq ( s , len ) { var ones = new Array ( len + 1 ) . fill ( 0 ) ; var zeroes = new Array ( len + 1 ) . fill ( 0 ) ; for ( var i = 0 ; i < len ; i ++ ) { if ( s [ i ] === " " ) { ones [ i + 1 ] = ones [ i ] + 1 ; zeroes [ i + 1 ] = zeroes [ i ] ; } else { zeroes [ i + 1 ] = zeroes [ i ] + 1 ; ones [ i + 1 ] = ones [ i ] ; } } var answer = - 2147483648 ; var x = 0 ; for ( var i = 0 ; i <= len ; i ++ ) { for ( var j = i ; j <= len ; j ++ ) { x += ones [ i ] ; x += zeroes [ j ] - zeroes [ i ] ; x += ones [ len ] - ones [ j ] ; answer = Math . max ( answer , x ) ; x = 0 ; } } document . write ( answer ) ; } var s = " " ; var len = s . length ; longestSubseq ( s , len ) ;