Queries to find minimum sum of array elements from either end of an array | Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver Code
function calculateQuery ( arr , N , query , M ) { var prefix = 0 , suffix = 0 ; var mp = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { prefix += arr [ i ] ; if ( ! mp . has ( arr [ i ] ) ) { mp . set ( arr [ i ] , [ 0 , 0 ] ) ; } var tmp = mp . get ( arr [ i ] ) ; tmp [ 0 ] = prefix ; mp . set ( arr [ i ] , tmp ) ; } for ( var i = N - 1 ; i >= 0 ; i -- ) { suffix += arr [ i ] ; if ( ! mp . has ( arr [ i ] ) ) { mp . set ( arr [ i ] , [ 0 , 0 ] ) ; } var tmp = mp . get ( arr [ i ] ) ; tmp [ 1 ] = suffix ; mp . set ( arr [ i ] , tmp ) ; } for ( var i = 0 ; i < M ; i ++ ) { var X = query [ i ] ; var tmp = mp . get ( X ) ; document . write ( Math . min ( tmp [ 0 ] , tmp [ 1 ] ) + " " ) ; } } var arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 30 ] ; var queries = [ 6 , 5 ] ; var N = arr . length ; var M = queries . length ; calculateQuery ( arr , N , queries , M ) ;