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 elements from either ends ; Traverse the query array ; Traverse the array from the front ; If element equals val , then break out of loop ; Traverse the array from rear ; If element equals val , break ; Print the minimum of the two as the answer ; Driver Code ; Function Call
import java . util . * ; class GFG { static void minSum ( int arr [ ] , int N , int Q [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int val = Q [ i ] ; int front = 0 , rear = 0 ; for ( int j = 0 ; j < N ; j ++ ) { front += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } for ( int j = N - 1 ; j >= 0 ; j -- ) { rear += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } System . out . print ( Math . min ( front , rear ) + " ▁ " ) ; } } 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 ; minSum ( arr , N , Q , M ) ; } }