#P12341. One-Dimensional Elimination Game
One-Dimensional Elimination Game
One-Dimensional Elimination Game
You are given a string \(S = S_0S_1\ldots S_{n-1}\) of length \(n\) consisting solely of characters \(A\) and \(B\). You can perform a sequence of operations on \(S\). In each operation, you select two indices \(i, j\) with \(0 \le i < j \le n-1\) such that \(S_i = A\) and \(S_j = B\), and then remove both characters simultaneously.
The operations continue until no valid move exists. That is, the process terminates when there is no pair \(i, j\) satisfying \(S_i = A\) and \(S_j = B\). Equivalently, the game stops when the remaining string is safe—its characters appear in such an order that no \(A\) occurs before a \(B\); in other words, the final string is of the form \(B\cdots B A\cdots A\).
Your task is to determine the maximum number of characters that can remain at the end of the game.
Observation: It can be shown that if the initial string is already safe (i.e. all the \(B\)'s appear before any \(A\)), then no move is possible and the answer is \(n\). Otherwise, regardless of the chosen sequence of removals, the game eventually forces the removal of certain pairs, and the final count always equals \(|\#A - \#B|\), where \(\#A\) and \(\#B\) denote the number of characters \(A\) and \(B\) in \(S\), respectively.
inputFormat
The input consists of two lines. The first line contains an integer \(n\) representing the length of the string. The second line contains the string \(S\) which is made up only of the characters \(A\) and \(B\).
outputFormat
Output a single integer: the maximum number of characters that can remain after performing the operations until no valid move exists.
sample
2
AB
0