Maximum equlibrium sum in an array | Function to find maximum equilibrium sum . ; Array to store prefix sum . ; Array to store suffix sum . ; Variable to store maximum sum . ; Calculate prefix sum . ; Calculate suffix sum and compare it with prefix sum . Update ans accordingly . ; Driver code
function findMaxSum ( arr , n ) { let preSum = new Array ( n ) ; preSum . fill ( 0 ) ; let suffSum = new Array ( n ) ; suffSum . fill ( 0 ) ; let ans = Number . MIN_VALUE ; preSum [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) preSum [ i ] = preSum [ i - 1 ] + arr [ i ] ; suffSum [ n - 1 ] = arr [ n - 1 ] ; if ( preSum [ n - 1 ] == suffSum [ n - 1 ] ) ans = Math . max ( ans , preSum [ n - 1 ] ) ; for ( let i = n - 2 ; i >= 0 ; i -- ) { suffSum [ i ] = suffSum [ i + 1 ] + arr [ i ] ; if ( suffSum [ i ] == preSum [ i ] ) ans = Math . max ( ans , preSum [ i ] ) ; } return ans ; } let arr = [ - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 ] ; let n = arr . length ; document . write ( findMaxSum ( arr , n ) ) ;