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)
assert Solution().calPoints(["5", "2", "C", "D", "+"]) == 30
assert Solution().calPoints(["5", "-2", "4", "C", "D", "9", "+", "+"]) == 27
assert Solution().calPoints(["1", "C"]) == 0
class Solution {
public int calPoints(String[] operations) {
Deque<Integer> st = new ArrayDeque<>();
for (String op : operations) {
if (op.equals("C")) st.pop();
else if (op.equals("D")) st.push(2 * st.peek());
else if (op.equals("+")) { int top = st.pop(), sum = top + st.peek(); st.push(top); st.push(sum); }
else st.push(Integer.parseInt(op));
}
int total = 0;
for (int v : st) total += v;
return total;
}
}
func calPoints(operations []string) int {
st := []int{}
for _, op := range operations {
n := len(st)
switch op {
case "C":
st = st[:n-1]
case "D":
st = append(st, 2*st[n-1])
case "+":
st = append(st, st[n-1]+st[n-2])
default:
v, _ := strconv.Atoi(op)
st = append(st, v)
}
}
sum := 0
for _, x := range st {
sum += x
}
return sum
}