Maximise array sum after taking non | Javascript implementation of the approach ; To store the states of dp ; To check if a given state has been solved ; To store the prefix - sum ; Function to fill the prefix_sum [ ] with the prefix sum of the given array ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code ; Finding prefix - sum ; Finding the maximum possible sum
var maxLen = 10 var dp = Array ( maxLen ) ; var v = Array ( maxLen ) ; var prefix_sum = Array ( maxLen ) ; ; function findPrefixSum ( arr , n ) { prefix_sum [ 0 ] = arr [ 0 ] ; for ( var i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = arr [ i ] + prefix_sum [ i - 1 ] ; } function maxSum ( arr , i , n , k ) { if ( i + k > n ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = 1 ; var x ; if ( i == 0 ) x = prefix_sum [ k - 1 ] ; else x = prefix_sum [ i + k - 1 ] - prefix_sum [ i - 1 ] ; dp [ i ] = Math . max ( maxSum ( arr , i + 1 , n , k ) , x + maxSum ( arr , i + k + 1 , n , k ) ) ; return dp [ i ] ; } var arr = [ 1 , 3 , 7 , 6 ] ; var n = arr . length ; var k = 1 ; findPrefixSum ( arr , n ) ; document . write ( maxSum ( arr , 0 , n , k ) ) ;