Queries to find the minimum array sum possible by removing elements from either end | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( int arr [ ] , int N , int Q [ ] , int M ) { map < int , int > m1 , m2 ; int front = 0 , rear = 0 ; for ( int i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 . insert ( { arr [ i ] , front } ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 . insert ( { arr [ i ] , rear } ) ; } for ( int i = 0 ; i < M ; i ++ ) { cout << min ( m1 [ Q [ i ] ] , m2 [ Q [ i ] ] ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q [ ] = { 7 , 6 } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; minOperations ( arr , N , Q , M ) ; return 0 ; }