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
1 <= operations.length <= 1000operations[i]is"C","D","+", or a string representing an integer in the range[-3 * 10^4, 3 * 10^4].- For operation
"+", there will always be at least two previous scores on the record. - For operations
"C"and"D", there will always be at least one previous score on the record.
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
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization