Maximum subsequence sum with adjacent elements having atleast K difference in index | Function to find the maximum sum subsequence such that two adjacent element have atleast difference of K in their indices ; DP Array to store the maximum sum obtained till now ; Either select the first element or Nothing ; Either Select the ( i - 1 ) element or let the previous best answer be the current best answer ; Either select the best sum till previous_index or select the current element + best_sum till index - k ; Driver Code
function max_sum ( arr , n , k ) { var dp = Array . from ( { length : n } , ( _ , i ) => 0 ) ; dp [ 0 ] = Math . max ( 0 , arr [ 0 ] ) ; var i = 1 ; while ( i < k ) { dp [ i ] = Math . max ( dp [ i - 1 ] , arr [ i ] ) ; i ++ ; } i = k ; while ( i < n ) { dp [ i ] = Math . max ( dp [ i - 1 ] , arr [ i ] + dp [ i - k ] ) ; i ++ ; } return dp [ n - 1 ] ; } var arr = [ 1 , 2 , - 2 , 4 , 3 , 1 ] ; var n = arr . length ; var k = 4 ; document . write ( max_sum ( arr , n , k ) ) ;