#K78857. Minimum Command Removal to Return to Origin
Minimum Command Removal to Return to Origin
Minimum Command Removal to Return to Origin
You are given a robot starting at the origin \((0, 0)\). The robot receives a sequence of \(n\) commands, each of which is one of the characters: 'U' (up), 'D' (down), 'L' (left) or 'R' (right). Executing a command moves the robot by 1 unit in the corresponding direction.
Your task is to determine the minimum number of commands that must be removed from the given sequence so that the final position of the robot becomes \((0, 0)\). If it is impossible to achieve \((0, 0)\) by removing commands, output \(-1\).
Let the net displacement along the x-axis be \(dx = \text{#R} - \text{#L}\) and along the y-axis be \(dy = \text{#U} - \text{#D}\). If it is possible to return to the origin by removing some commands, the minimum removals required is given by \[ \text{removals} = |dx| + |dy|, \] provided that \(|dx|+|dy|\) is even. Otherwise, output \(-1\).
Note: The removal of a command eliminates its effect completely.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains an integer \(n\) representing the number of commands.
- The second line contains a string of length \(n\) consisting of the characters 'U', 'D', 'L', and 'R' representing the sequence of commands.
outputFormat
Print a single integer representing the minimum number of commands that must be removed so that the robot returns to the origin \((0, 0)\). If it is impossible, print \(-1\).
## sample6
UUDLRL
2
</p>