Maximum sum subsequence with values differing by at least 2 | function to find maximum sum subsequence such that two adjacent values elements are not selected ; map to store the frequency of array elements ; make a dp array to store answer upto i th value ; base cases ; iterate for all possible values of arr [ i ] ; return the last value ; Driver function
function get_max_sum ( arr , n ) { var freq = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( freq . has ( arr [ i ] ) ) freq . set ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) else freq . set ( arr [ i ] , 1 ) } var dp = Array ( 100001 ) . fill ( 0 ) ; dp [ 0 ] = 0 ; dp [ 1 ] = ( freq . has ( 0 ) ? freq . get ( 0 ) : 0 ) ; for ( var i = 2 ; i <= 100000 ; i ++ ) { dp [ i ] = Math . max ( dp [ i - 1 ] , dp [ i - 2 ] + i * ( freq . has ( i ) ? freq . get ( i ) : 0 ) ) ; } return dp [ 100000 ] ; } var N = 3 ; var arr = [ 2 , 2 , 3 ] ; document . write ( get_max_sum ( arr , N ) ) ;