Range sum queries based on given conditions | Java program for the above approach ; Function to calculate the sum between the given range as per value of m ; Stores the sum ; Condition for a to print the sum between ranges [ a , b ] ; Return sum ; Function to precalculate the sum of both the vectors ; Make Prefix sum array ; Function to compute the result for each query ; Take a dummy vector and copy the element of arr in brr ; Sort the dummy vector ; Compute prefix sum of both vectors ; Performs operations ; Function call to find sum ; Function call to find sum ; Driver Code ; Given arr [ ] ; Number of queries ; Given queries ; Function call
import java . util . * ; class GFG { static int range_sum ( int [ ] arr , int a , int b ) { int sum = 0 ; if ( a - 2 < 0 ) sum = arr [ b - 1 ] ; else sum = arr [ b - 1 ] - arr [ a - 2 ] ; return sum ; } static void precompute_sum ( int [ ] arr , int [ ] brr ) { int N = ( int ) arr . length ; for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; brr [ i ] = brr [ i ] + brr [ i - 1 ] ; } } static void find_sum ( int [ ] arr , int q , int Queries [ ] [ ] ) { int [ ] brr = arr . clone ( ) ; int N = ( int ) arr . length ; Arrays . sort ( brr ) ; precompute_sum ( arr , brr ) ; for ( int i = 0 ; i < q ; i ++ ) { int m = Queries [ i ] [ 0 ] ; int a = Queries [ i ] [ 1 ] ; int b = Queries [ i ] [ 2 ] ; if ( m == 1 ) { System . out . print ( range_sum ( arr , a , b ) + " ▁ " ) ; } else if ( m == 2 ) { System . out . print ( range_sum ( brr , a , b ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 6 , 4 , 2 , 7 , 2 , 7 } ; int Q = 1 ; int Queries [ ] [ ] = { { 2 , 3 , 6 } } ; find_sum ( arr , Q , Queries ) ; } }