Traverse the string
for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( charVal ( S . charAt ( i ) ) < charVal ( S . charAt ( i + 1 ) ) ) res -= charVal ( S . charAt ( i ) ) ; else res += charVal ( S . charAt ( i ) ) ; }