Use a stack of valid round scores so cancel, double, and sum operations can access the required recent values directly.
Complexity
O(n) time and O(n) space.
Evaluate a sequence of baseball scoring operations and return the total score.
Use a stack of valid round scores so cancel, double, and sum operations can access the required recent values directly.
O(n) time and O(n) space.
package main
import "strconv"
func calPoints(operations []string) int {
scores := []int{}
for _, operation := range operations {
switch operation {
case "+":
scores = append(scores, scores[len(scores)-1]+scores[len(scores)-2])
case "D":
scores = append(scores, scores[len(scores)-1]*2)
case "C":
scores = scores[:len(scores)-1]
default:
score, _ := strconv.Atoi(operation)
scores = append(scores, score)
}
}
total := 0
for _, score := range scores {
total += score
}
return total
}
class Solution:
def calPoints(self, operations: list[str]) -> int:
scores: list[int] = []
for operation in operations:
if operation == "+": scores.append(scores[-1] + scores[-2])
elif operation == "D": scores.append(scores[-1] * 2)
elif operation == "C": scores.pop()
else: scores.append(int(operation))
return sum(scores)
function calPoints(operations: string[]): number {
const scores: number[] = [];
for (const operation of operations) {
if (operation === "+") scores.push(scores.at(-1)! + scores.at(-2)!);
else if (operation === "D") scores.push(scores.at(-1)! * 2);
else if (operation === "C") scores.pop();
else scores.push(Number(operation));
}
return scores.reduce((sum, score) => sum + score, 0);
}