Menu
CoddyTech

Baseball Game

EasyStackpython iconjava iconcpp iconc iconjs icon+10

You keep score for an unusual game. The list operations is read from left to right, and each entry changes a record of scores. An integer such as "7" or "-2" adds that score to the record. "+" adds a score equal to the sum of the two latest scores, "D" adds a score equal to twice the latest score, and "C" removes the latest score from the record for good.

Write a function named calPoints that returns the sum of the scores left on the record after the last operation. An empty record sums to 0.

Function

calPoints(operations: string-array) → integer
operationsstring-array
the operations in order: integers as text, or "+", "D", "C"
Returnsinteger
the sum of the scores still on the record at the end

Constraints

  • 1 ≤ operations.length ≤ 5000
  • Each entry is "+", "D", "C", or an integer written in decimal with -3 × 104 ≤ value ≤ 3 × 104.
  • Every operation is valid: "+" comes only when the record holds at least two scores, "D" and "C" only when it holds at least one.
  • Every score on the record and the final sum fit in a 32-bit signed integer.

Examples

Input
operations = ["4", "-2", "D", "+", "C", "7"]
Output
5
Explanation
The record grows to [4, -2], "D" adds -4, "+" adds -2 + -4 = -6, "C" removes that -6, and 7 goes on last. The record [4, -2, -4, 7] sums to 5.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Can you return the sum without adding up the record at the end, so that every operation, a cancel included, takes O(1) time?

Reset code
def calPoints(operations):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

operations = ["4", "-2", "D", "+", "C", "7"]

Expected

5