Skip to main content
Back to problems
#682
Easy Algorithms

Baseball game

Array Stack Simulation
80.1% acceptance
Feb 20, 2026
3319
1963
Baseball game: simulate operations and return sum of all scores.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn cal_points(operations: Vec<String>) -> i32 {
    let mut stack: Vec<i32> = Vec::new();
    for op in &operations {
      match op.as_str() {
        "C" => { stack.pop(); }
        "D" => {
          let last = *stack.last().unwrap();
          stack.push(last * 2);
        }
        "+" => {
          let n = stack.len();
          stack.push(stack[n - 1] + stack[n - 2]);
        }
        s => { stack.push(s.parse().unwrap()); }
      }
    }
    stack.iter().sum()
  }
}