Range queries for alternatively addition and subtraction on given Array | C ++ program for the above approach ; 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 ; Driver Code ; Given array ; Given Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int L , R ; } ; void fillPrefixArray ( int arr [ ] , int n , int prefixArray [ ] ) { prefixArray [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { prefixArray [ i ] = prefixArray [ i - 1 ] + arr [ i ] ; } else { prefixArray [ i ] = prefixArray [ i - 1 ] - arr [ i ] ; } } } int findResultUtil ( int prefixArray [ ] , int L , int R ) { int result ; if ( L == 0 ) { result = prefixArray [ R ] ; } else { result = prefixArray [ R ] - prefixArray [ L - 1 ] ; } if ( L & 1 ) { result = result * ( -1 ) ; } return result ; } void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { int prefixArray [ n ] ; fillPrefixArray ( arr , n , prefixArray ) ; for ( int i = 0 ; i < m ; i ++ ) { cout << findResultUtil ( prefixArray , q [ i ] . L , q [ i ] . R ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query q [ ] = { { 2 , 5 } , { 6 , 8 } , { 1 , 7 } , { 4 , 8 } , { 0 , 5 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; findResult ( arr , n , q , m ) ; return 0 ; }