Range queries for alternatively addition and subtraction on given Array | 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
def findResultUtil ( arr , L , R ) : NEW_LINE INDENT result = 0 NEW_LINE flag = False NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( flag == False ) : NEW_LINE INDENT result = result + arr [ i ] NEW_LINE flag = True NEW_LINE DEDENT else : NEW_LINE INDENT result = result - arr [ i ] NEW_LINE flag = False NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def findResult ( arr , n , q , m ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT print ( findResultUtil ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 ] NEW_LINE n = len ( arr ) NEW_LINE q = [ [ 2 , 5 ] , [ 6 , 8 ] , [ 1 , 7 ] , [ 4 , 8 ] , [ 0 , 5 ] ] NEW_LINE m = len ( q ) NEW_LINE findResult ( arr , n , q , m ) NEW_LINE DEDENT