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  $left[$n]; $right[$n]; ; 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
< ? php function maximum_one ( $ s , $ n ) { $ cnt_one = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == '1' ) $ cnt_one ++ ; } if ( $ s [ 0 ] == '1' ) $ left [ 0 ] = 1 ; else $ left [ 0 ] = 0 ; if ( $ s [ $ n - 1 ] == '1' ) $ right [ $ n - 1 ] = 1 ; else $ right [ $ n - 1 ] = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == '1' ) $ left [ $ i ] = $ left [ $ i - 1 ] + 1 ; else $ left [ $ i ] = 0 ; } for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { if ( $ s [ $ i ] == '1' ) $ right [ $ i ] = $ right [ $ i + 1 ] + 1 ; else $ right [ $ i ] = 0 ; } $ cnt = 0 ; $ max_cnt = 0 ; for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ s [ $ i ] == '0' ) { $ sum = $ left [ $ i - 1 ] + $ right [ $ i + 1 ] ; if ( $ sum < $ cnt_one ) $ cnt = $ sum + 1 ; else $ cnt = $ sum ; $ max_cnt = max ( $ max_cnt , $ cnt ) ; $ cnt = 0 ; } } return $ max_cnt ; } $ s = "111011101" ; echo maximum_one ( $ s , strlen ( $ s ) ) ; ? >