Queries to find the minimum array sum possible by removing elements from either end | Function to find the minimum sum for each query after removing element from either ends till each value Q [ i ] ; Stores the prefix sum from both the ends of the array ; Traverse the array from front ; Insert it into the map m1 ; Traverse the array in reverse ; Insert it into the map m2 ; Traverse the query array ; Print the minimum of the two values as the answer ; Driver Code ; Function Call
def minOperations ( arr , N , Q , M ) : NEW_LINE INDENT m1 = { } NEW_LINE m2 = { } NEW_LINE front = 0 NEW_LINE rear = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT front += arr [ i ] NEW_LINE m1 [ arr [ i ] ] = front NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT rear += arr [ i ] NEW_LINE m2 [ arr [ i ] ] = rear NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT print ( min ( m1 [ Q [ i ] ] , m2 [ Q [ i ] ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE Q = [ 7 , 6 ] NEW_LINE M = len ( Q ) NEW_LINE minOperations ( arr , N , Q , M ) NEW_LINE