Range queries for alternatively addition and subtraction on given Array | Structure to represent a query ; This function fills the Prefix Array ; Initialise the prefix array ; Iterate all the element of arr [ ] and update the prefix array ; If n is even then , add the previous value of prefix array with the current value of arr ; if n is odd , then subtract the previous value of prefix Array from current value ; Function to find the result of alternatively adding and subtracting elements in the range [ L < R ] ; Case 1 : when L is zero ; Case 2 : When L is non zero ; If L is odd means range starts from odd position multiply result by - 1 ; Return the final result ; Function to find the sum of all alternative add and subtract between ranges [ L , R ] ; Declare prefix array ; Function Call to fill prefix arr [ ] ; Iterate for each query ; Given array ; Given Queries ; Function Call
class Query { constructor ( l , r ) { this . L = l ; this . R = r ; } } function fillPrefixArray ( arr , n , prefixArray ) { prefixArray [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { prefixArray [ i ] = prefixArray [ i - 1 ] + arr [ i ] ; } else { prefixArray [ i ] = prefixArray [ i - 1 ] - arr [ i ] ; } } } function findResultUtil ( prefixArray , L , R ) { let result ; if ( L == 0 ) { result = prefixArray [ R ] ; } else { result = prefixArray [ R ] - prefixArray [ L - 1 ] ; } if ( L % 2 == 1 ) { result = result * ( - 1 ) ; } return result ; } function findResult ( arr , n , q , m ) { let prefixArray = new Array ( n ) ; fillPrefixArray ( arr , n , prefixArray ) ; for ( let i = 0 ; i < m ; i ++ ) { document . write ( findResultUtil ( prefixArray , q [ i ] . L , q [ i ] . R ) + " " ) ; } } let arr = [ 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 ] ; let n = arr . length ; let q = [ new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) ] ; let m = q . length ; findResult ( arr , n , q , m ) ;