Range sum queries based on given conditions | 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 ; Given [ ] arr ; Number of queries ; Given queries ; Function call
function range_sum ( arr , a , b ) { let sum = 0 ; if ( a - 2 < 0 ) sum = arr [ b - 1 ] ; else sum = arr [ b - 1 ] - arr [ a - 2 ] ; return sum ; } function precompute_sum ( arr , brr ) { let N = arr . length ; for ( let i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; brr [ i ] = brr [ i ] + brr [ i - 1 ] ; } } function find_sum ( arr , q , Queries ) { let brr = [ ... arr ] ; let N = arr . length ; brr . sort ( function ( a , b ) { return a - b ; } ) ; precompute_sum ( arr , brr ) ; for ( let i = 0 ; i < q ; i ++ ) { let m = Queries [ i ] [ 0 ] ; let a = Queries [ i ] [ 1 ] ; let b = Queries [ i ] [ 2 ] ; if ( m == 1 ) { document . write ( range_sum ( arr , a , b ) + " " ) ; } else if ( m == 2 ) { document . write ( range_sum ( brr , a , b ) + " " ) ; } } } let arr = [ 0 , 6 , 4 , 2 , 7 , 2 , 7 ] ; let Q = 1 ; let Queries = [ [ 2 , 3 , 6 ] ] ; find_sum ( arr , Q , Queries ) ;