Maximize the Sum of a Subsequence from an Array based on given conditions | JavaScript program to implement the above approach ; Function to select the array elements to maximize the sum of the selected elements ; If the entire array is solved ; Memoized subproblem ; Calculate sum considering the current element in the subsequence ; Calculate sum without considering the current element in the subsequence ; Update the maximum of the above sums in the dp [ ] [ ] table ; Driver Code ; Initialize the dp array ; Function call
var N = 6 ; function maximumSum ( a , count , index , n , dp ) { if ( index == n ) return 0 ; if ( dp [ index ] [ count ] != - 1 ) return dp [ index ] [ count ] ; var take_element = a [ index ] * count + maximumSum ( a , count + 1 , index + 1 , n , dp ) ; var dont_take = maximumSum ( a , count , index + 1 , n , dp ) ; return dp [ index ] [ count ] = Math . max ( take_element , dont_take ) ; } var n = 5 ; var a = [ - 1 , - 9 , 0 , 5 , - 7 ] ; var dp = Array . from ( Array ( N ) , ( ) => Array ( N ) . fill ( - 1 ) ) ; document . write ( maximumSum ( a , 1 , 0 , n , dp ) ) ;