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 ; Driver Code ; Given arr [ ] ; Number of queries ; Given queries ; Function Call
def range_sum ( arr , a , b ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( a - 2 < 0 ) : NEW_LINE INDENT sum = arr [ b - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT sum = ( arr [ b - 1 ] - arr [ a - 2 ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def precompute_sum ( arr , brr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] = arr [ i ] + arr [ i - 1 ] NEW_LINE brr [ i ] = brr [ i ] + brr [ i - 1 ] NEW_LINE DEDENT DEDENT def find_sum ( arr , q , Queries ) : NEW_LINE INDENT brr = arr . copy ( ) NEW_LINE N = len ( arr ) NEW_LINE brr . sort ( ) NEW_LINE precompute_sum ( arr , brr ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT m = Queries [ i ] [ 0 ] NEW_LINE a = Queries [ i ] [ 1 ] NEW_LINE b = Queries [ i ] [ 2 ] NEW_LINE if ( m == 1 ) : NEW_LINE INDENT print ( range_sum ( arr , a , b ) , end = ' ▁ ' ) NEW_LINE DEDENT elif ( m == 2 ) : NEW_LINE INDENT print ( range_sum ( brr , a , b ) , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 6 , 4 , 2 , 7 , 2 , 7 ] NEW_LINE Q = 1 NEW_LINE Queries = [ [ 2 , 3 , 6 ] ] NEW_LINE find_sum ( arr , Q , Queries ) NEW_LINE DEDENT