Maximum sum in an array such that every element has exactly one adjacent element to it | Javascript implementation of the approach ; To store the states of dp ; Function to return the maximized sum ; Base case ; Checks if a state is already solved ; Recurrence relation ; Return the result ; Driver code
var arrSize = 51 ; var dp = Array ( arrSize ) ; var v = Array ( arrSize ) ; function sumMax ( i , arr , n ) { if ( i >= n - 1 ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = true ; dp [ i ] = Math . max ( arr [ i ] + arr [ i + 1 ] + sumMax ( i + 3 , arr , n ) , sumMax ( i + 1 , arr , n ) ) ; return dp [ i ] ; } var arr = [ 1 , 1 , 1 , 1 ] ; var n = arr . length ; document . write ( sumMax ( 0 , arr , n ) ) ;