Skip to content

682. Baseball Game

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int calPoints(vector<string>& operations) {
    vector<int> scores;

    for (const string& operation : operations)
      if (operation == "+")
        scores.push_back(scores.back() + scores[scores.size() - 2]);
      else if (operation == "D")
        scores.push_back(scores.back() * 2);
      else if (operation == "C")
        scores.pop_back();
      else
        scores.push_back(stoi(operation));

    return accumulate(scores.begin(), scores.end(), 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int calPoints(String[] operations) {
    Deque<Integer> scores = new ArrayDeque<>();

    for (final String operation : operations) {
      switch (operation) {
        case "+":
          final int lastScore = scores.pop();
          final int secondLastScore = scores.peek();
          scores.push(lastScore);
          scores.push(lastScore + secondLastScore);
          break;
        case "D":
          scores.push(scores.peek() * 2);
          break;
        case "C":
          scores.pop();
          break;
        default:
          scores.push(Integer.parseInt(operation));
      }
    }

    return scores.stream().mapToInt(Integer::intValue).sum();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def calPoints(self, operations: list[str]) -> int:
    scores = []

    for operation in operations:
      match operation:
        case '+':
          scores.append(scores[-1] + scores[-2])
        case 'D':
          scores.append(scores[-1] * 2)
        case 'C':
          scores.pop()
        case default:
          scores.append(int(operation))

    return sum(scores)