Baseball Game
Keep a score record that operations add to, double, combine and cancel, then add up what is left.
A game is scored with a few unusual rules. The record of scores starts empty, and each string in the array operations
- an integer x, such as
or"5" : record a new score x;"-2" : record a new score, the sum of the previous two scores;"+" : record a new score, double the previous score;"D" : remove the previous score from the record."C"
Return the sum of all scores on the record after the last operation. Every operation is valid, so "+""D""C"
Example 1
Output: 30
Explanation: the record ends as [5, 10, 15].
Example 2
Output: 27
Explanation: the record ends as [5, -2, -4, 9, 5, 14].
The Idea
Think of a scorekeeper with a notepad. Each new score goes on a new line at the bottom of the list. When a score is cancelled, the scorekeeper crosses out the last line. When a rule needs "the previous score", the scorekeeper looks at the last line that is not crossed out.
Follow Example 1 on that notepad. "5""2""C""D""D""+"
Notice where all the work happens. Every rule writes at the end of the list, crosses out at the end, or reads one or two scores from the end. Nothing ever touches the middle. And when the last score is crossed out, the one before it becomes "the previous score" again.
A pile of plates works the same way: you put a plate on top and take a plate from the top. In programming such a pile is called a stack. Putting a value on top is a push, taking the top value off is a pop, and reading the top value without taking it off is a peek. Look at the picture below.
Each column shows the record as a stack after one operation of Example 1, with the newest score on top. Under "C""D""+"
So the record is a stack of scores. Each operation is one or two stack moves, and the answer is the sum of whatever is left on the stack at the end.
Solution Approach
Turning that idea into code means settling three things: which Java class holds the record, how "+"
The class that holds the record
Which Java class gives us a stack? ArrayDequejava.utilDequepushpoppeekStackDeque
With that, three of the operations are one move each. A number is pushed. "D""C"
Reaching the score below the top
What about "+"peek
Adding up the record
When does the total get computed? Only at the end. A running total would have to be corrected on every "C"
Java Solution
The method calPoints
- First, create the record as an empty stack,
.Deque<Integer> record = new ArrayDeque<>() - Loop over
, one stringoperations at a time, and pick the case for it with aop . The switch uses the arrow form,switch , from Java 14, so each case runs only its own code and needs nocase "+" -> .break - For
, pop the top score into"+" , add the score now on top intolast , then pushsum back and pushlast .sum - For
, push twice the top score. For"D" , pop the top score. Any other string is a number: the"C" case turns it into andefault withint , which also reads a minus sign such as the one inInteger.parseInt , and pushes it."-2" - After the loop, a second loop adds every score left in
intorecord , and the method returnstotal .total
The main"C""+"
import java.util.ArrayDeque;
import java.util.Deque;
public class BaseballGame {
public static int calPoints(String[] operations) {
Deque<Integer> record = new ArrayDeque<>();
for (String op : operations) {
switch (op) {
case "+" -> {
int last = record.pop(); // take the newest score off
int sum = last + record.peek(); // add the one now on top
record.push(last); // put the newest score back
record.push(sum);
}
case "D" -> record.push(2 * record.peek());
case "C" -> record.pop();
default -> record.push(Integer.parseInt(op));
}
}
int total = 0;
for (int score : record) {
total += score;
}
return total;
}
public static void main(String[] args) {
System.out.println(calPoints(new String[] {"5", "2", "C", "D", "+"}));
System.out.println(calPoints(new String[] {"5", "-2", "4", "C", "D", "9", "+", "+"}));
System.out.println(calPoints(new String[] {"3", "4", "+", "C", "+"}));
System.out.println(calPoints(new String[] {"-3", "D", "+"}));
System.out.println(calPoints(new String[] {"1", "C"}));
}
}
Running it prints:
30
27
14
-18
0
The 30 and 27 at the top match the two examples. The 14 comes from ["3", "4", "+", "C", "+"]"+""C""+"
The -18 shows that negative scores need nothing special: -3 is doubled to -6, then "+""C"total
The line record.push(last)"+"
The original implementation,
Complexity
The work is one pass over the operations, then one pass over the scores left on the record.
- Time: O(n) for n operations. Each operation does at most one pop, one peek and two pushes, each a fixed number of steps on an
, and the final loop visits at most n scores.ArrayDeque - Space: O(n) for the record. Every number,
and"D" adds one score, so with no"+" at all the record holds n scores."C"
A stack that holds values for operators to combine is also how