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 readonly 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
using System ; class GFG { class Query { public int L , R ; public Query ( int l , int r ) { L = l ; R = r ; } } ; static 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 ] ; } } } static 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 % 2 == 1 ) { result = result * ( - 1 ) ; } return result ; } static void findResult ( int [ ] arr , int n , Query [ ] q , int m ) { int [ ] prefixArray = new int [ n ] ; fillPrefixArray ( arr , n , prefixArray ) ; for ( int i = 0 ; i < m ; i ++ ) { Console . Write ( findResultUtil ( prefixArray , q [ i ] . L , q [ i ] . R ) + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = arr . Length ; Query [ ] q = { new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) } ; int m = q . Length ; findResult ( arr , n , q , m ) ; } }