Maximum sum subsequence with values differing by at least 2 | C # program to find 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 code
using System ; using System . Collections . Generic ; class GFG { public static int get_max_sum ( int [ ] arr , int n ) { Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . ContainsKey ( arr [ i ] ) ) { int x = freq [ arr [ i ] ] ; freq [ arr [ i ] ] = x + 1 ; } else freq . Add ( arr [ i ] , 1 ) ; } int [ ] dp = new int [ 100001 ] ; for ( int i = 0 ; i < 100001 ; i ++ ) dp [ i ] = 0 ; dp [ 0 ] = 0 ; if ( freq . ContainsKey ( 0 ) ) dp [ 1 ] = freq [ 0 ] ; else dp [ 1 ] = 0 ; for ( int i = 2 ; i <= 100000 ; i ++ ) { int temp = ( freq . ContainsKey ( i ) ) ? freq [ i ] : 0 ; dp [ i ] = Math . Max ( dp [ i - 1 ] , dp [ i - 2 ] + i * temp ) ; } return dp [ 100000 ] ; } public static void Main ( String [ ] args ) { int N = 3 ; int [ ] arr = { 2 , 2 , 3 } ; Console . WriteLine ( get_max_sum ( arr , N ) ) ; } }