Maximum sum of non | Javascript program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum for sub - array { i , j } ; Required recurrence relation ; Returning the value ; Input array
let maxLen = 10 ; let dp = new Array ( maxLen ) ; let visit = new Array ( maxLen ) ; function maxSum ( arr , i , n , k ) { if ( i >= n ) return 0 ; if ( visit [ i ] ) return dp [ i ] ; visit [ i ] = true ; let tot = 0 ; dp [ i ] = maxSum ( arr , i + 1 , n , k ) ; for ( let j = i ; j < ( i + k ) && ( j < n ) ; j ++ ) { tot += arr [ j ] ; dp [ i ] = Math . max ( dp [ i ] , tot + maxSum ( arr , j + 2 , n , k ) ) ; } return dp [ i ] ; } let arr = [ - 1 , 2 , - 3 , 4 , 5 ] ; let k = 2 ; let n = arr . length ; document . write ( maxSum ( arr , 0 , n , k ) ) ;