LeetCode 682: Baseball Game Solution

Master LeetCode problem 682 (Baseball Game), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

682. Baseball Game

Problem Explanation

Explanation

To solve this problem, we can use a stack data structure to keep track of the record of scores. We iterate through each operation in the input list and perform the corresponding action. If the operation is to add a new score, we push it onto the stack. If the operation is to add the sum of previous two scores, we pop the last two scores, calculate their sum, and push it back onto the stack. If the operation is to double the previous score, we double the last score and push it back onto the stack. If the operation is to invalidate the previous score, we pop the last score from the stack. Finally, we sum up all the scores remaining in the stack to get the total sum.

Time Complexity

The time complexity of this approach is O(n) where n is the number of operations in the input list.

Space Complexity

The space complexity is also O(n) where n is the number of operations in the input list.


Solution Code

class Solution {
    public int calPoints(String[] ops) {
        Stack<Integer> stack = new Stack<>();
        
        for (String op : ops) {
            if (op.equals("C")) {
                stack.pop();
            } else if (op.equals("D")) {
                stack.push(stack.peek() * 2);
            } else if (op.equals("+")) {
                int last = stack.pop();
                int secondLast = stack.peek();
                stack.push(last);
                stack.push(last + secondLast);
            } else {
                stack.push(Integer.parseInt(op));
            }
        }
        
        int sum = 0;
        for (int score : stack) {
            sum += score;
        }
        
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 682 (Baseball Game)?

This page provides optimized solutions for LeetCode problem 682 (Baseball Game) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 682 (Baseball Game)?

The time complexity for LeetCode 682 (Baseball Game) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 682 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 682 in Java, C++, or Python.

Back to LeetCode Solutions