Maximum sum possible for a sub | Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first element and second element will be k indices apart ; Fill remaining positions ; Return the maximum sum ; Driver code
def maxSum ( arr , k , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] ; NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return max ( arr [ 0 ] , arr [ 1 ] ) ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] = max ( arr [ i ] , dp [ i - 1 ] ) ; NEW_LINE DEDENT for i in range ( k + 1 , n ) : NEW_LINE INDENT dp [ i ] = max ( arr [ i ] , dp [ i - ( k + 1 ) ] + arr [ i ] ) ; NEW_LINE DEDENT max_element = max ( dp ) ; NEW_LINE return max_element ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 7 , 1 , 3 , 8 , 2 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( maxSum ( arr , k , n ) ) ; NEW_LINE DEDENT