You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds’ scores.
At the beginning of the game, you start with an empty record. You are given a list of strings ops
, where ops[i]
is the ith
operation you must apply sequentially to the record and it can be one of the following:
x
– Record a new score of x
."+"
– 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.
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record -> [5]
"2" - Add 2 to the record -> [5, 2]
"C" - Invalidate and remove the previous score -> [5]
"D" - Add 2 * 5 to the record -> [5, 10]
"+" - Add 5 + 10 to the record -> [5, 10, 15]
The sum is 5 + 10 + 15 = 30
1 <= ops.length <= 1000
ops[i]
is "C"
, "D"
, "+"
, or a string representing an integer in the range [-3 * 10^4, 3 * 10^4]
."+"
, there will always be at least two previous scores on the record."D"
, there will always be at least one previous score on the record."C"
, there will always be at least one previous score on the record."+"
operation, there will be at least two scores before it.
"+"
, push the sum of the last two scores in the record."D"
, push the double of the last score in the record."C"
, pop the last score from the record.#include <vector>
#include <string>
#include <numeric> // for accumulate
using namespace std;
class Solution {
public:
int calPoints(vector<string>& ops) {
vector<int> record;
for (const string& op : ops) {
if (op == "C") {
record.pop_back();
} else if (op == "D") {
record.push_back(2 * record.back());
} else if (op == "+") {
record.push_back(record[record.size() - 1] + record[record.size() - 2]);
} else {
record.push_back(stoi(op));
}
}
// Calculate the sum of the elements in the record.
return accumulate(record.begin(), record.end(), 0);
}
};
The time complexity of this solution is (O(n)), where (n) is the number of operations in the ops
list. This is because we are iterating through the list of operations once and each operation is processed in constant time.
record
to keep track of the scores.ops
list:
record
."C"
, remove the last score from the record
."D"
, push the double of the last score in the record
."+"
, push the sum of the last two scores in the record
.std::accumulate
to sum all the scores in the record
and return the result.This solution efficiently handles all the rules specified in the problem statement and respects all constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?