SDE & MLE Prep

682. Baseball Game

Problem

Keep a baseball score record from operations: an integer records that score, "+" records the sum of the previous two scores, "D" doubles the previous score, and "C" removes the previous score. Return the sum of the final record.

Example: ["5","2","C","D","+"] → 30 (record 5, 10, 15)

The record is a stack of scores: a number pushes, C pops, D pushes double the top, + pushes the sum of the top two. Answer = sum of the stack.

Complexity: O(n).

class Solution:
    def calPoints(self, operations: List[str]) -> int:
        st = []
        for op in operations:
            if op == "C":
                st.pop()
            elif op == "D":
                st.append(2 * st[-1])
            elif op == "+":
                st.append(st[-1] + st[-2])
            else:
                st.append(int(op))
        return sum(st)