Problem Description
Given a list of operations representing tracked scores, update the score record based on the following rules:
- 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 twice the previous score.
- "C": Invalidate the previous score, removing it from the record. Return the sum of all scores after processing all operations.
Key Insights
- Use a stack (list) to keep track of valid scores.
- Process operations sequentially, updating the stack accordingly.
- Handle different operations by manipulating the stack: push new scores, pop invalid scores.
- Final result is the sum of scores left in the stack.
Space and Time Complexity
Time Complexity: O(n), where n is the number of operations. Space Complexity: O(n), in the worst-case the stack stores all operation results.
Solution
The solution uses a stack-based approach. Iterate through each operation and:
- If the operation is a numeric value, convert it to an integer and push it onto the stack.
- If it is "C", remove the most recent score by popping from the stack.
- If it is "D", double the most recent score and push the result.
- If it is "+", calculate the sum of the two most recent scores and push that value. Finally, sum all the values in the stack to obtain the final score.