Queries to find minimum sum of array elements from either end of an array | 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
function calculateQuery ( arr , N , query , M ) { for ( let i = 0 ; i < M ; i ++ ) { let X = query [ i ] ; let sum_start = 0 , sum_end = 0 ; for ( let j = 0 ; j < N ; j ++ ) { sum_start += arr [ j ] ; if ( arr [ j ] == X ) break ; } for ( let j = N - 1 ; j >= 0 ; j -- ) { sum_end += arr [ j ] ; if ( arr [ j ] == X ) break ; } document . write ( Math . min ( sum_end , sum_start ) + " " ) ; } } let arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 30 ] ; let queries = [ 6 , 5 ] ; let N = arr . length ; let M = queries . length ; calculateQuery ( arr , N , queries , M ) ;