You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations
, where operations[i]
is the i<sup>th</sup>
operation you must apply to the record and is one of the following:
An integer
x
.- Record a new score of
x
.
- Record a new score of
'+'
.- Record a new score that is the sum of the previous two scores.
'D'
.- Record a new score that is the double of the previous score.
'C'
.- Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
LeetCode Problem - 682
import java.util.Objects;
import java.util.Stack;
class Solution {
// Method to calculate the sum of valid points in a list of operations
public int calPoints(String[] operations) {
// Stack to store points
Stack<Integer> stack = new Stack<>();
// String representing valid operations
String flag = "DC+";
// Iterate through the operations
for (String operation : operations) {
// Check if the operation is a valid operation
if (flag.contains(operation)) {
// If the operation is '+', double the sum of the last two valid points and push onto stack
if (Objects.equals(operation, "+")) {
int top = stack.pop();
int second = stack.pop();
stack.push(second);
stack.push(top);
stack.push(top + second);
}
// If the operation is 'D', double the last valid point and push onto stack
else if (Objects.equals(operation, "D")) {
int top = stack.pop();
stack.push(top);
stack.push(top * 2);
}
// If the operation is 'C', remove the last valid point from stack
else {
stack.pop();
}
}
// If the operation is a number, parse it and push onto stack
else {
int operationValue = Integer.parseInt(operation);
stack.push(operationValue);
}
}
// Calculate the sum of valid points in the stack
int ans = 0;
for (int e : stack) {
ans += e;
}
// Return the sum of valid points
return ans;
}
}