Maximum sum in an array such that every element has exactly one adjacent element to it | Python 3 implementation of the approach ; To store the states of dp ; Function to return the maximized sum ; Base case ; Checks if a state is already solved ; Recurrence relation ; Return the result ; Driver code
arrSize = 51 NEW_LINE dp = [ 0 for i in range ( arrSize ) ] NEW_LINE v = [ False for i in range ( arrSize ) ] NEW_LINE def sumMax ( i , arr , n ) : NEW_LINE INDENT if ( i >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT v [ i ] = True NEW_LINE dp [ i ] = max ( arr [ i ] + arr [ i + 1 ] + sumMax ( i + 3 , arr , n ) , sumMax ( i + 1 , arr , n ) ) NEW_LINE return dp [ i ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumMax ( 0 , arr , n ) ) NEW_LINE DEDENT