Precompute the sum of products for all index
for j in range ( 0 , Len , 1 ) : NEW_LINE INDENT if ( S [ j ] == '0' ) : NEW_LINE INDENT count_zero += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count_one += 1 ; NEW_LINE DEDENT dp [ j ] = count_zero * count_one ; NEW_LINE DEDENT