# Calculate sum of the array generated by given operations

Calculate sum of the array generated by given operations

Given an array arr[] consisting of N strings, the task is to find the total sum of the array brr[] (initially empty) constructed by performing following operations while traversing the given array arr[]:

Examples:

Input: arr[] = {“5”, “2”, “C”, “D”, “+”}Output: 30Explanation:While traversing the array arr[], the array brr[] is modified as:

“5” – Add 5 to the array brr[]. Now, the array brr[] modifies to {5}.

“2” – Add 2 to the array brr[]. Now, the array brr[] modifies to {5, 2}.

“C” – Remove the last element from the array brr[]. Now, the array brr[] modifies to {5}.

“D” – Add twice the last element of the array brr[] to the array brr[]. Now, the array brr[] modifies to {5, 10}.

“+” – Add the sum of the last two elements of the array brr[] to the array brr[]. Now the array brr[] modifies to {5, 10, 15}.

After performing the above operations, the total sum of the array brr[] is 5 + 10 + 15 = 30.

Input: arr[] = {“5”, “-2”, “4”, “C”, “D”, “9”, “+”, “+”}Output: 27

Approach: The idea to solve the given problem is to use a Stack. Follow the steps below to solve the problem:

Initialize a stack of integers, say S, and initialize a variable, say ans as 0, to store the resultant sum of the array formed.

Traverse the given array arr[] and perform the following steps:

If the value of arr[i] is “C”, then subtract the top element of the stack from the ans and pop it from S.

If the value of arr[i] is “D”, then push twice the top element of the stack S in the stack S and then add its value to ans.

If the value of arr[i] is “+”, then push the value of the sum of the top two elements of the stack S and add their sum to ans.

Otherwise, push arr[i] to the stack S, and add its value to ans.

After the loop, print the value of ans as the result.

Below is the implementation of the above approach:

C++

#include

using namespace std;

void findTotalSum(vector& ops)

{

if (ops.empty()) {

cout