Calculate sum of the array generated by given operations | Java 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
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 ) ; } }