Length of longest consecutive ones by at most one swap in a Binary String | Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; string
function maximum_one ( s , n ) { var cnt_one = 0 ; var max_cnt = 0 , temp = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) { cnt_one ++ ; temp ++ ; } else { max_cnt = Math . max ( temp , max_cnt ) ; temp = 0 ; } } max_cnt = Math . max ( max_cnt , temp ) ; var left = Array ( n ) ; var right = Array ( n ) ; if ( s [ 0 ] == ' ' ) left [ 0 ] = 1 ; else left [ 0 ] = 0 ; if ( s [ n - 1 ] == ' ' ) right [ n - 1 ] = 1 ; else right [ n - 1 ] = 0 ; for ( var i = 1 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) left [ i ] = left [ i - 1 ] + 1 ; else left [ i ] = 0 ; } for ( var i = n - 2 ; i >= 0 ; i -- ) { if ( s [ i ] == ' ' ) right [ i ] = right [ i + 1 ] + 1 ; else right [ i ] = 0 ; } for ( var i = 1 ; i < n - 1 ; i ++ ) { if ( s [ i ] == ' ' ) { var sum = left [ i - 1 ] + right [ i + 1 ] ; if ( sum < cnt_one ) max_cnt = Math . max ( max_cnt , sum + 1 ) ; else max_cnt = Math . max ( max_cnt , sum ) ; } } return max_cnt ; } var s = " " ; document . write ( maximum_one ( s , s . length ) ) ;