Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ]
int pre_count_0 [ n + 2 ] ; int pre_count_1 [ n + 1 ] ; int post_count_0 [ n + 1 ] ; pre_count_0 [ 0 ] = 0 ; post_count_0 [ n + 1 ] = 0 ; pre_count_1 [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { pre_count_0 [ j ] = pre_count_0 [ j - 1 ] ; pre_count_1 [ j ] = pre_count_1 [ j - 1 ] ; post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] ; if ( s [ j - 1 ] == '0' ) pre_count_0 [ j ] ++ ; else pre_count_1 [ j ] ++ ; if ( s [ n - j ] == '0' ) post_count_0 [ n - j + 1 ] ++ ; }