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
def max_sum ( arr , n , k ) : NEW_LINE INDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = max ( 0 , arr [ 0 ] ) ; NEW_LINE i = 1 ; NEW_LINE while ( i < k ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , arr [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT i = k ; NEW_LINE while ( i < n ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , arr [ i ] + dp [ i - k ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT return dp [ n - 1 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , - 2 , 4 , 3 , 1 ] ; NEW_LINE n = len ( arr ) NEW_LINE k = 4 ; NEW_LINE print ( max_sum ( arr , n , k ) ) ; NEW_LINE DEDENT