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: 30
Explanation:
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 <bits/stdc++.h>
using namespace std;
void findTotalSum(vector<string>& ops)
{
if (ops.empty()) {
cout << 0;
return ;
}
stack< int > pts;
int ans = 0;
for ( int i = 0; i < ops.size(); i++) {
if (ops[i] == "C" ) {
ans -= pts.top();
pts.pop();
}
else if (ops[i] == "D" ) {
pts.push(pts.top() * 2);
ans += pts.top();
}
else if (ops[i] == "+" ) {
int a = pts.top();
pts.pop();
int b = pts.top();
pts.push(a);
ans += (a + b);
pts.push(a + b);
}
else {
int n = stoi(ops[i]);
ans += n;
pts.push(n);
}
}
cout << ans;
}
int main()
{
vector<string> arr = { "5" , "-2" , "C" , "D" , "+" };
findTotalSum(arr);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{
static void findTotalSum(String ops[])
{
if (ops.length == 0 )
{
System.out.println( 0 );
return ;
}
Stack<Integer> pts = new Stack<>();
int ans = 0 ;
for ( int i = 0 ; i < ops.length; i++) {
if (ops[i] == "C" ) {
ans -= pts.pop();
}
else if (ops[i] == "D" ) {
pts.push(pts.peek() * 2 );
ans += pts.peek();
}
else if (ops[i] == "+" ) {
int a = pts.pop();
int b = pts.peek();
pts.push(a);
ans += (a + b);
pts.push(a + b);
}
else {
int n = Integer.parseInt(ops[i]);
ans += n;
pts.push(n);
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
String arr[] = { "5" , "-2" , "C" , "D" , "+" };
findTotalSum(arr);
}
}
|
Python3
def findTotalSum(ops):
if ( len (ops) = = 0 ):
print ( 0 )
return
pts = []
ans = 0
for i in range ( len (ops)):
if (ops[i] = = "C" ):
ans - = pts[ - 1 ]
pts.pop()
elif (ops[i] = = "D" ):
pts.append(pts[ - 1 ] * 2 )
ans + = pts[ - 1 ]
elif (ops[i] = = "+" ):
a = pts[ - 1 ]
pts.pop()
b = pts[ - 1 ]
pts.append(a)
ans + = (a + b)
pts.append(a + b)
else :
n = int (ops[i])
ans + = n
pts.append(n)
print (ans)
if __name__ = = "__main__" :
arr = [ "5" , "-2" , "C" , "D" , "+" ]
findTotalSum(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void findTotalSum( string []ops)
{
if (ops.Length == 0)
{
Console.WriteLine(0);
return ;
}
Stack< int > pts = new Stack< int >();
int ans = 0;
for ( int i = 0; i < ops.Length; i++)
{
if (ops[i] == "C" )
{
ans -= pts.Pop();
}
else if (ops[i] == "D" )
{
pts.Push(pts.Peek() * 2);
ans += pts.Peek();
}
else if (ops[i] == "+" )
{
int a = pts.Pop();
int b = pts.Peek();
pts.Push(a);
ans += (a + b);
pts.Push(a + b);
}
else
{
int n = Int32.Parse(ops[i]);
ans += n;
pts.Push(n);
}
}
Console.WriteLine(ans);
}
public static void Main()
{
string []arr = { "5" , "-2" , "C" , "D" , "+" };
findTotalSum(arr);
}
}
|
Javascript
<script>
function findTotalSum(ops)
{
if (ops.length==0) {
document.write( 0);
return ;
}
var pts = [];
var ans = 0;
for ( var i = 0; i < ops.length; i++) {
if (ops[i] == "C" ) {
ans -= pts[pts.length-1];
pts.pop();
}
else if (ops[i] == "D" ) {
pts.push(pts[pts.length-1] * 2);
ans += pts[pts.length-1];
}
else if (ops[i] == "+" ) {
var a = pts[pts.length-1];
pts.pop();
var b = pts[pts.length-1];
pts.push(a);
ans += (a + b);
pts.push(a + b);
}
else {
var n = parseInt(ops[i]);
ans += n;
pts.push(n);
}
}
document.write( ans);
}
var arr = [ "5" , "-2" , "C" , "D" , "+" ];
findTotalSum(arr);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
10 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...