Queries to find minimum sum of array elements from either end of an array | C ++ implementation of the above approach ; Function to calculate the minimum sum from either end of the arrays for the given queries ; Traverse the query [ ] array ; Stores sum from start and end of the array ; Calculate distance from start ; Calculate distance from end ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calculateQuery ( int arr [ ] , int N , int query [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; int sum_start = 0 , sum_end = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum_start += arr [ j ] ; if ( arr [ j ] == X ) break ; } for ( int j = N - 1 ; j >= 0 ; j -- ) { sum_end += arr [ j ] ; if ( arr [ j ] == X ) break ; } cout << min ( sum_end , sum_start ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int queries [ ] = { 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; calculateQuery ( arr , N , queries , M ) ; return 0 ; }