Maximum sum such that no two elements are adjacent | Set 2 | 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 ; Required recurrence relation ; Returning the value ; Driver code
var maxLen = 10 ; var dp = Array ( maxLen ) ; var v = Array ( maxLen ) ; function maxSum ( arr , i , n ) { if ( i >= n ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = 1 ; dp [ i ] = Math . max ( maxSum ( arr , i + 1 , n ) , arr [ i ] + maxSum ( arr , i + 2 , n ) ) ; return dp [ i ] ; } var arr = [ 12 , 9 , 7 , 33 ] ; var n = arr . length ; document . write ( maxSum ( arr , 0 , n ) ) ;