EasyArrayStackSimulation

Baseball Game

LeetCode
1 approach, code in all languages

You are keeping a running record of scores for a game. You are given a list of string operations, each of which modifies the record in one of four ways.

An integer string x records a new score equal to x. The string "+" records a new score equal to the sum of the previous two scores. The string "D" records a new score equal to double the previous score. The string "C" cancels the previous score, removing it from the record.

Each operation is guaranteed to be valid: when "+", "D", or "C" is applied there are enough prior scores present. Return the sum of all scores remaining in the record after processing every operation.

Example 1

Input: operations = ["5","2","C","D","+"]

Output: 30

Record 5, then 2 -> [5,2]. "C" removes 2 -> [5]. "D" doubles to 10 -> [5,10]. "+" adds 5+10=15 -> [5,10,15]. Sum = 30.

Example 2

Input: operations = ["5","-2","4","C","D","9","+","+"]

Output: 27

Record 5, -2, 4 -> [5,-2,4]. "C" removes 4 -> [5,-2]. "D" doubles -2 to -4 -> [5,-2,-4]. Record 9 -> [5,-2,-4,9]. "+" -> -4+9=5 -> [...,5]. "+" -> 9+5=14. Sum = 5-2-4+9+5+14 = 27.

Constraints

  • 1 <= operations.length <= 1000
  • operations[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 10^4, 3 * 10^4]
  • For "+", the record has at least two prior scores; for "C" and "D" it has at least one
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now