A remote relay station is controlled by a punched command tape read by its onboard controller. The tape has n numbered lines (0-indexed), each containing one of three commands: CHARGE x (add x units to the station's power reserve), DRAIN x (attempt to remove x units from the reserve), or HALT (stop the tape immediately).
The read head starts at line 0 with reserve 0. Repeatedly:
HALT, the tape stops immediately and no more lines run.CHARGE x: add x to the reserve, then move the head to the next line.DRAIN x: if reserve - x >= 0, subtract x from the reserve and move the head to the next line; otherwise leave the reserve unchanged and move the head back one line instead.Given the full tape, determine the reserve level at the exact moment the tape stops.
Line 1: a single integer n, the number of tape lines.
Each of the next n lines contains one command: either CHARGE x, DRAIN x, or HALT.
Print a single integer: the reserve level when execution stops.
Example 1
Input
3 CHARGE 5 DRAIN 3 HALT
Expected
2
Explanation
Line 0 CHARGE 5 raises the reserve to 5 and the head moves to line 1. Line 1 DRAIN 3: 5 - 3 = 2 >= 0, so the reserve becomes 2 and the head moves to line 2. Line 2 is HALT, so the tape stops. Final reserve is 2.
Example 2
Input
4 CHARGE 2 DRAIN 5 DRAIN 1 CHARGE 10
Expected
2
Explanation
Line 0 CHARGE 2 raises the reserve to 2 and the head moves to line 1. Line 1 DRAIN 5: 2 - 5 = -3 < 0, so the reserve stays at 2 and the head moves back to line 0 instead of forward. Line 0 has already fired, so the controller stops the tape immediately without re-running it. Lines 2 and 3 never execute, and the final reserve is 2.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →