Maximize sum of remaining elements after every removal of the array half with greater sum | js program to implement the above approach ; Function to find the maximum sum ; Base Case ; Check if ( mapped key is found in the dictionary ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right values ; Store the value in dp array ; Return the final answer ; Function to print maximum sum ; Stores prefix sum ; Store results of subproblems ; Traversing the array ; Add prefix sum of array ; Print the answer ; Driver Code ; Function call
let dp = [ ] ; for ( let i = 0 ; i < 100 ; i ++ ) { dp [ i ] = [ ] ; for ( let j = 0 ; j < 100 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } function maxweight ( s , e , pre ) { if ( s == e ) return 0 ; if ( dp [ s ] [ e ] != - 1 ) return dp [ s ] [ e ] ; let ans = 0 ; for ( let i = s ; i < e ; i ++ ) { let left = pre [ i ] - pre [ s - 1 ] ; let right = pre [ e ] - pre [ i ] ; if ( left < right ) ans = Math . max ( ans , Number ( left + maxweight ( s , i , pre ) ) ) ; if ( left == right ) ans = Math . max ( ans , Math . max ( left + maxweight ( s , i , pre ) , right + maxweight ( i + 1 , e , pre ) ) ) ; if ( left > right ) ans = Math . max ( ans , right + maxweight ( i + 1 , e , pre ) ) ; dp [ s ] [ e ] = ans ; } return dp [ s ] [ e ] ; } function maxSum ( arr , n ) { let pre = new Map ( ) ; pre [ - 1 ] = 0 ; pre [ 0 ] = arr [ 0 ] ; for ( let i = 0 ; i < 100 ; i ++ ) { for ( let j = 0 ; j < 100 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } for ( let i = 0 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + arr [ i ] ; document . write ( maxweight ( 0 , n - 1 , pre ) ) ; } let arr = [ 6 , 2 , 3 , 4 , 5 , 5 ] ; maxSum ( arr , 6 ) ;