AAlgoLoopSpaced repetition for LeetCode
EASYStack / QueueLeetCode ↗

Baseball Game

The key idea

Each operation only ever touches the most recent valid scores, so a stack is the perfect record. Push an integer, pop on C, push double-of-top on D, and push the sum of the top two on +. The answer is the sum of everything still on the stack at the end.

Problem

You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.

You are given a list of strings operations, where operations[i] is the i-th operation you must apply to the record and is one of the following:

- An integer x — Record a new score of x.
- "+" — Record a new score that is the sum of the previous two scores.
- "D" — Record a new score that is the double of the previous score.
- "C" — Invalidate the previous score, removing it from the record.

Return the sum of all the scores on the record after applying all the operations. The test cases are generated so the answer fits in a 32-bit integer, and every operation is valid.

Constraints

Examples

Input: operations = ["5","2","C","D","+"] Output: 30
Input: operations = ["5","-2","4","C","D","9","+","+"] Output: 27
Input: operations = ["1"] Output: 1

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Stack / Queue problems