Stacks and Queues Matching and cancelling
199. Baseball Game
You are keeping the score of a game with unusual rules. A record of scores starts empty, and you are given
a list of strings operations, applied to it in order. Each operation is one of these:
- An integer
x, such as"7"or"-3": add a new score ofxto the record. "+": add a new score equal to the sum of the two most recent scores in the record."D": add a new score equal to twice the most recent score in the record."C": cancel the most recent score in the record, removing it.
A cancelled score is gone for good, so later operations never see it. Return the sum of the scores left in the record after the last operation.
Example 1
Input: operations = ["3", "8", "+", "D", "C", "-4", "+"]
25Explanation: The record grows to [3, 8, 11, 22]. "C" removes 22, and "-4" adds −4. The last "+" adds
11 + (−4) = 7. The record ends as [3, 8, 11, −4, 7], which sums to 25.
Example 2
Input: operations = ["-6", "D", "+", "C", "C"]
-6Explanation: The record grows to [−6, −12, −18]. The two cancels remove −18 and then −12, so only −6 is left.
Example 3
Input: operations = ["1000000000", "1000000000", "+", "D"]
8000000000Explanation: The record ends as 109, 109, 2 × 109 and 4 × 109.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ operations.length ≤ 105- Each
operations[i]is"+","D","C"or an integer from-109to109, written in decimal with no leading zeros - A
"+"comes only when the record holds at least two scores, and a"D"or"C"only when it holds at least one - Every score added to the record is between
-1010and1010
Clarifying questions
What you would ask an interviewer before writing any code.