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
function minOperations ( arr , N , Q , M ) { var m1 = new Map ( ) ; var m2 = new Map ( ) ; var front = 0 , rear = 0 ; var i ; for ( i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 . set ( arr [ i ] , front ) ; } for ( i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 . set ( arr [ i ] , rear ) ; } for ( i = 0 ; i < M ; i ++ ) { document . write ( Math . min ( m1 . get ( Q [ i ] ) , m2 . get ( Q [ i ] ) ) + " " ) ; } } var arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 1 ] ; var N = arr . length ; var Q = [ 7 , 6 ] ; var M = Q . length ; minOperations ( arr , N , Q , M ) ;