Stores the count of valid substrings
for ( int i = 0 ; i < n ; i ++ ) { if ( pref [ i ] > 0 ) cnt ++ ; } reverse ( pref . begin ( ) , pref . end ( ) ) ; int inversions = CountInversions ( pref ) ; int ans = cnt + inversions ; return ans ; }