human
What is a code to maximum sum such that exactly half of the elements are selected and no two adjacent and the other steps required given the following:
Maximum sum such that exactly half of the elements are selected and no two adjacent | Function return the maximum sum possible under given condition.
Base case.
When i is odd.
When i is even.
Maximum of if we pick last element or not.
Driver code"
Solution in Python:
assistant
#Here is code to maximum sum such that exactly half of the elements are selected and no two adjacent and the other steps required.
 def MaximumSum ( a , n ) :
	dp = [ [ 0 for x in range ( 2 ) ] for y in range ( n + 1 ) ]
	dp [ 2 ] [ 1 ] = a [ 1 ]
	dp [ 2 ] [ 0 ] = a [ 0 ]
	for i in range ( 3 , n + 1 ) :
		if ( i & 1 ) :
			temp = max ( [ dp [ i - 3 ] [ 1 ] , dp [ i - 3 ] [ 0 ] , dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] ] )
			dp [ i ] [ 1 ] = a [ i - 1 ] + temp
			dp [ i ] [ 0 ] = max ( [ a [ i - 2 ] + dp [ i - 2 ] [ 0 ] , a [ i - 2 ] + dp [ i - 3 ] [ 1 ] , a [ i - 2 ] + dp [ i - 3 ] [ 0 ] , a [ i - 3 ] + dp [ i - 3 ] [ 0 ] ] )
		else :
			dp [ i ] [ 1 ] = ( a [ i - 1 ] + max ( [ dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] , dp [ i - 1 ] [ 0 ] ] ) )
			dp [ i ] [ 0 ] = a [ i - 2 ] + dp [ i - 2 ] [ 0 ]
	return max ( dp [ n ] [ 1 ] , dp [ n ] [ 0 ] )
if __name__ == " _ _ main _ _ " :
	A = [ 1 , 2 , 3 , 4 , 5 , 6 ]
	N = len ( A )
	print ( MaximumSum ( A , N ) )