Stores the count of valid substrings
for i in range ( n ) : NEW_LINE INDENT if ( pref [ i ] > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT pref = pref [ : - 1 ] NEW_LINE inversions = CountInversions ( pref ) NEW_LINE ans = cnt + inversions + 1 NEW_LINE return ans NEW_LINE