Maximum sum of non | Python3 program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum for sub - array { i , j } ; Required recurrence relation ; Returning the value ; Driver code ; Input array
maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE visit = [ 0 ] * maxLen ; NEW_LINE def maxSum ( arr , i , n , k ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( visit [ i ] ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT visit [ i ] = 1 ; NEW_LINE tot = 0 ; NEW_LINE dp [ i ] = maxSum ( arr , i + 1 , n , k ) ; NEW_LINE j = i NEW_LINE while ( j < i + k and j < n ) : NEW_LINE INDENT tot += arr [ j ] ; NEW_LINE dp [ i ] = max ( dp [ i ] , tot + maxSum ( arr , j + 2 , n , k ) ) ; NEW_LINE j += 1 NEW_LINE DEDENT return dp [ i ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , - 3 , 4 , 5 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxSum ( arr , 0 , n , k ) ) ; NEW_LINE DEDENT