424. Scorekeeper

A quiz show keeps a running list of round scores. You receive a list of operations, applied in order. An integer string such as "8" or "-3" records a new round with that score. "C" cancels the most recent score still on the list and removes it. "D" records a new score equal to double the latest score on the list. "+" records a new score equal to the sum of the latest two scores.

After all operations are applied, return the total of the scores that remain on the list. Every operation is valid when it is applied (there are always enough scores for it), and every recorded score and the final total fit in a 32-bit signed integer.

Example 1

Input:
ops = ["8","-3","D","+","C","12","+"]
Output:
17
Explanation:

The list grows 8, -3, -6, then + adds -9, which C removes again. After recording 12, the + adds 12 + (-6) = 6. Remaining scores: 8, -3, -6, 12, 6, total 17.

Example 2

Input:
ops = ["40","15","C","C","7","D","D","+"]
Output:
91
Explanation:

40 and 15 are recorded and both cancelled. Then 7, 14, 28 and 14 + 28 = 42 follow, so the total is 7 + 14 + 28 + 42 = 91.

Constraints

1 ≤ ops.length ≤ 1000
Each operation is "C", "D", "+", or an integer between -30000 and 30000.
Every operation is applicable at the moment it is performed.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…