Queries to find minimum sum of array elements from either end of an array | Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver Code
def calculateQuery ( arr , N , query , M ) : NEW_LINE INDENT prefix = 0 NEW_LINE suffix = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefix += arr [ i ] NEW_LINE mp [ arr [ i ] ] = [ prefix , 0 ] NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT suffix += arr [ i ] NEW_LINE mp [ arr [ i ] ] = [ mp [ arr [ i ] ] [ 0 ] , suffix ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT X = query [ i ] NEW_LINE print ( min ( mp [ X ] [ 0 ] , mp [ X ] [ 1 ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 30 ] NEW_LINE queries = [ 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( queries ) NEW_LINE calculateQuery ( arr , N , queries , M ) NEW_LINE