Range queries for alternatively addition and subtraction on given Array | Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; if flag is false , then add & toggle the flag ; if flag is true subtract and toggle the flag ; Return the final result ; Function to find the value for each query ; Iterate for each query ; Given array ; Given Queries ; Function Call
function findResultUtil ( arr , L , R ) { var result = 0 ; var flag = false ; for ( var i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } function findResult ( arr , n , q , m ) { for ( var i = 0 ; i < m ; i ++ ) { document . write ( findResultUtil ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) + " " ) ; } } var arr = [ 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 ] ; var n = arr . length ; var q = [ [ 2 , 5 ] , [ 6 , 8 ] , [ 1 , 7 ] , [ 4 , 8 ] , [ 0 , 5 ] ] ; var m = q . length ; findResult ( arr , n , q , m ) ;