Baseball Game - 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 such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
Input & Output
Example 1 — Mixed Operations
$
Input:
operations = ["5","2","C","D","+"]
›
Output:
30
💡 Note:
"5" → [5], "2" → [5,2], "C" → [5], "D" → [5,10], "+" → [5,10,15]. Sum = 5+10+15 = 30
Example 2 — Simple Numbers
$
Input:
operations = ["5","-2","4","C","D","9","+","+"]
›
Output:
27
💡 Note:
"5" → [5], "-2" → [5,-2], "4" → [5,-2,4], "C" → [5,-2], "D" → [5,-2,-4], "9" → [5,-2,-4,9], "+" → [5,-2,-4,9,5], "+" → [5,-2,-4,9,5,14]. Sum = 27
Example 3 — Only Numbers
$
Input:
operations = ["1"]
›
Output:
1
💡 Note:
Single operation adds 1 to record. Sum = 1
Constraints
- 1 ≤ operations.length ≤ 1000
- operations[i] is "C", "D", "+", or a string representing an integer in range [-3 × 104, 3 × 104]
- 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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of string operations: ["5","2","C","D","+"]
2
Process
Apply each operation to modify the score record
3
Output
Sum of all valid scores: 30
Key Takeaway
🎯 Key Insight: Stack data structure naturally handles last-in operations like cancel, double, and sum-previous-two
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code