Calculate sum of the array generated by given operations
Last Updated :
10 Jun, 2021
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
void findTotalSum(vector<string>& ops)
{
// If the size of array is 0
if (ops.empty()) {
cout << 0;
return;
}
stack<int> pts;
// Stores the required sum
int ans = 0;
// Traverse the array ops[]
for (int i = 0; i < ops.size(); i++) {
// If the character is C, remove
// the top element from the stack
if (ops[i] == "C") {
ans -= pts.top();
pts.pop();
}
// If the character is D, then push
// 2 * top element into stack
else if (ops[i] == "D") {
pts.push(pts.top() * 2);
ans += pts.top();
}
// If the character is +, add sum
// of top two elements from the stack
else if (ops[i] == "+") {
int a = pts.top();
pts.pop();
int b = pts.top();
pts.push(a);
ans += (a + b);
pts.push(a + b);
}
// Otherwise, push x
// and add it to ans
else {
int n = stoi(ops[i]);
ans += n;
pts.push(n);
}
}
// Print the resultant sum
cout << ans;
}
// Driver Code
int main()
{
vector<string> arr = { "5", "-2", "C", "D", "+" };
findTotalSum(arr);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
static void findTotalSum(String ops[])
{
// If the size of array is 0
if (ops.length == 0)
{
System.out.println(0);
return;
}
Stack<Integer> pts = new Stack<>();
// Stores the required sum
int ans = 0;
// Traverse the array ops[]
for (int i = 0; i < ops.length; i++) {
// If the character is C, remove
// the top element from the stack
if (ops[i] == "C") {
ans -= pts.pop();
}
// If the character is D, then push
// 2 * top element into stack
else if (ops[i] == "D") {
pts.push(pts.peek() * 2);
ans += pts.peek();
}
// If the character is +, add sum
// of top two elements from the stack
else if (ops[i] == "+") {
int a = pts.pop();
int b = pts.peek();
pts.push(a);
ans += (a + b);
pts.push(a + b);
}
// Otherwise, push x
// and add it to ans
else {
int n = Integer.parseInt(ops[i]);
ans += n;
pts.push(n);
}
}
// Print the resultant sum
System.out.println(ans);
}
// Driver Code
public static void main(String[] args)
{
String arr[] = { "5", "-2", "C", "D", "+" };
findTotalSum(arr);
}
}
// This code is contributed by Kingash.
Python3
# Python3 program for the above approach
# Function to find the sum of the array
# formed by performing given set of
# operations while traversing the array ops[]
def findTotalSum(ops):
# If the size of array is 0
if (len(ops) == 0):
print(0)
return
pts = []
# Stores the required sum
ans = 0
# Traverse the array ops[]
for i in range(len(ops)):
# If the character is C, remove
# the top element from the stack
if (ops[i] == "C"):
ans -= pts[-1]
pts.pop()
# If the character is D, then push
# 2 * top element into stack
elif (ops[i] == "D"):
pts.append(pts[-1] * 2)
ans += pts[-1]
# If the character is +, add sum
# of top two elements from the stack
elif (ops[i] == "+"):
a = pts[-1]
pts.pop()
b = pts[-1]
pts.append(a)
ans += (a + b)
pts.append(a + b)
# Otherwise, push x
# and add it to ans
else:
n = int(ops[i])
ans += n
pts.append(n)
# Print the resultant sum
print(ans)
# Driver Code
if __name__ == "__main__":
arr = ["5", "-2", "C", "D", "+"]
findTotalSum(arr)
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
static void findTotalSum(string []ops)
{
// If the size of array is 0
if (ops.Length == 0)
{
Console.WriteLine(0);
return;
}
Stack<int> pts = new Stack<int>();
// Stores the required sum
int ans = 0;
// Traverse the array ops[]
for(int i = 0; i < ops.Length; i++)
{
// If the character is C, remove
// the top element from the stack
if (ops[i] == "C")
{
ans -= pts.Pop();
}
// If the character is D, then push
// 2 * top element into stack
else if (ops[i] == "D")
{
pts.Push(pts.Peek() * 2);
ans += pts.Peek();
}
// If the character is +, add sum
// of top two elements from the stack
else if (ops[i] == "+")
{
int a = pts.Pop();
int b = pts.Peek();
pts.Push(a);
ans += (a + b);
pts.Push(a + b);
}
// Otherwise, push x
// and add it to ans
else
{
int n = Int32.Parse(ops[i]);
ans += n;
pts.Push(n);
}
}
// Print the resultant sum
Console.WriteLine(ans);
}
// Driver Code
public static void Main()
{
string []arr = { "5", "-2", "C", "D", "+" };
findTotalSum(arr);
}
}
// This code is contributed by ipg2016107
JavaScript
<script>
// JavaScript program for the above approach
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
function findTotalSum(ops)
{
// If the size of array is 0
if (ops.length==0) {
document.write( 0);
return;
}
var pts = [];
// Stores the required sum
var ans = 0;
// Traverse the array ops[]
for (var i = 0; i < ops.length; i++) {
// If the character is C, remove
// the top element from the stack
if (ops[i] == "C") {
ans -= pts[pts.length-1];
pts.pop();
}
// If the character is D, then push
// 2 * top element into stack
else if (ops[i] == "D") {
pts.push(pts[pts.length-1] * 2);
ans += pts[pts.length-1];
}
// If the character is +, add sum
// of top two elements from the stack
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);
}
// Otherwise, push x
// and add it to ans
else {
var n = parseInt(ops[i]);
ans += n;
pts.push(n);
}
}
// Print the resultant sum
document.write( ans);
}
// Driver Code
var arr = ["5", "-2", "C", "D", "+" ];
findTotalSum(arr);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Restore the original array from another array generated by given operations Given an array b. The array b is obtained initially by array a, by doing the following operations. Choose a fixed point x from array a.Cyclically rotate the array a to the left exactly x times.Fixed point x is that point where (a[i] = i ). These operations are performed on the array a k times, deter
8 min read
Program to generate an array having convolution of two given arrays Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to construct a convolution array C[] of size (N + M - 1). The convolution of 2 arrays is defined as C[i + j] = ?(a[i] * b[j]) for every i and j. Note: If the value for any index becomes very large, then print it to
15+ min read
Find the increased sum of the Array after P operations Given an array arr[] of non-negative integers of size N and an integer P. Neighboring values of every non-zero element are incremented by 2 in each operation, the task is to find the increased sum of the array after P operations. Examples: Input: arr[] = {0, 5, 0, 4, 0}, P = 2Output: 24Explanation:
12 min read
Number of operations such that size of the Array becomes 1 Given an array A[] of N positive integers. The task is to find the number of operations such that the size of the array becomes 1 at the end of operations. The operation to be performed is: In the current array, let X be the maximum element and Y be the minimum element. Let Z=X%Y. If Z is 0, remove
8 min read
Find the final sequence of the array after performing given operations Given an array arr[] of size N, the task is to perform the following operation exactly N times, Create an empty list of integers b[] and in the ith operation, Append arr[i] to the end of b[].Reverse the elements in b[]. Finally, print the contents of the list b[] after the end of all operations.Exam
12 min read