Calculate sum of the array generated by given operations | C ++ 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 [ ] ; If the size of array is 0 ; Stores the required sum ; Traverse the array ops [ ] ; If the character is C , remove the top element from the stack ; If the character is D , then push 2 * top element into stack ; If the character is + , add sum of top two elements from the stack ; Otherwise , push x and add it to ans ; Print the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE 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 ; }