Calculate sum of the array generated by given operations | 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
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 ] == " " ) { ans -= pts [ pts . length - 1 ] ; pts . pop ( ) ; } else if ( ops [ i ] == " " ) { 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 = [ " " , " " , " " , " " , " " ] ; findTotalSum ( arr ) ;