Queries to find the minimum array sum possible by removing elements from either end | Java program for the above approach ; 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
import java . util . * ; class GFG { static void minOperations ( int [ ] arr , int N , int [ ] Q , int M ) { Map < Integer , Integer > m1 = new HashMap < Integer , Integer > ( ) ; Map < Integer , Integer > m2 = new HashMap < Integer , Integer > ( ) ; int front = 0 , rear = 0 ; for ( int i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 . put ( arr [ i ] , front ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 . put ( arr [ i ] , rear ) ; } for ( int i = 0 ; i < M ; i ++ ) { System . out . print ( Math . min ( m1 . get ( Q [ i ] ) , m2 . get ( Q [ i ] ) ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = arr . length ; int [ ] Q = { 7 , 6 } ; int M = Q . length ; minOperations ( arr , N , Q , M ) ; } }