Queries to find minimum sum of array elements from either end of an array | C # implementation of the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { static void calculateQuery ( int [ ] arr , int N , int [ ] query , int M ) { int prefix = 0 , suffix = 0 ; Dictionary < int , Tuple < int , int > > mp = new Dictionary < int , Tuple < int , int > > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { prefix += arr [ i ] ; mp [ arr [ i ] ] = new Tuple < int , int > ( prefix , 0 ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { suffix += arr [ i ] ; mp [ arr [ i ] ] = new Tuple < int , int > ( mp [ arr [ i ] ] . Item1 , suffix ) ; } for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; Console . Write ( Math . Min ( mp [ X ] . Item1 , mp [ X ] . Item2 ) + " ▁ " ) ; } } static void Main ( ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int [ ] queries = { 6 , 5 } ; int N = arr . Length ; int M = queries . Length ; calculateQuery ( arr , N , queries , M ) ; } }