Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Baseball Game Scores

Easy · Stack & Queue · Asked at Amazon, Microsoft, TCS, Infosys, Wipro

You keep a list of scores and process operations in order:

Every operation is valid (there are enough scores). Print the sum of the scores at the end.

Input

First line: n. Second line: the n operations separated by spaces.

Output

The total of the remaining scores.

Constraints

A stack holds the recorded scores: push for numbers, +, D; pop for C. Sum the stack at the end. Values can grow quickly with repeated D and +, so use 64-bit integers.

Example 1

Input

5
5 2 C D +

Output

30

Example 2

Input

8
5 -2 4 C D 9 + +

Output

27

Hints

  1. Every operation looks only at the most recent scores — a stack.
  2. + reads the top two, D reads the top one, C removes the top.

Approach

Process the tokens in order with a stack of recorded scores: a number is pushed; + pushes top + second; D pushes 2 × top; C pops. The answer is the sum of what remains. Repeated doubling can grow quickly, so store 64-bit values.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<long long> st;
    for (int i = 0; i < n; i++) {
        string op;
        cin >> op;
        if (op == "+") st.push_back(st[st.size() - 1] + st[st.size() - 2]);
        else if (op == "D") st.push_back(2 * st.back());
        else if (op == "C") st.pop_back();
        else st.push_back(stoll(op));
    }
    long long total = 0;
    for (long long x : st) total += x;
    cout << total << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
st = []
for op in data[1 : 1 + n]:
    if op == "+":
        st.append(st[-1] + st[-2])
    elif op == "D":
        st.append(2 * st[-1])
    elif op == "C":
        st.pop()
    else:
        st.append(int(op))
print(sum(st))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        br.readLine();
        ArrayList<Long> st = new ArrayList<>();
        for (String op : br.readLine().trim().split("\\s+")) {
            int k = st.size();
            if (op.equals("+")) st.add(st.get(k - 1) + st.get(k - 2));
            else if (op.equals("D")) st.add(2 * st.get(k - 1));
            else if (op.equals("C")) st.remove(k - 1);
            else st.add(Long.parseLong(op));
        }
        long total = 0;
        for (long x : st) total += x;
        System.out.println(total);
    }
}

Solve Baseball Game Scores online · All practice problems