[
stack
simulation
]
Leetcode 0682 Baseball Game
Problem statement
https://leetcode.com/problems/baseball-game/
Solution
Not very clear what to do, but when you realize it is quite easy. Just do what is asked, using stack: if we have +, we need to add sum of two last elements into stack. If we have C, we remove last element. If we have D, we add doubled last element. If we have number, we just append it.
Complexity
Time and space complexity is O(n).
Code
class Solution:
def calPoints(self, ops):
stack = []
for op in ops:
if op == '+':
stack.append(stack[-1] + stack[-2])
elif op == 'C':
stack.pop()
elif op == 'D':
stack.append(2 * stack[-1])
else:
stack.append(int(op))
return sum(stack)