Range queries for alternatively addition and subtraction on given Array | Java program for the above approach ; Structure to represent a range query ; 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 ; Driver Code ; Given array ; Given Queries ; Function call
import java . util . * ; class GFG { static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static int findResultUtil ( int arr [ ] , int L , int R ) { int result = 0 ; boolean flag = false ; for ( int i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } static void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { System . out . print ( findResultUtil ( arr , 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 ) ; } }