human
Write me a code to maximum Sum Subsequence made up of consecutive elements of different parity and the other steps required given the following:
Maximum Sum Subsequence made up of consecutive elements of different parity | Function to calculate the maximum sum subsequence with consecutive terms having different parity.
Base Case.
Store the parity of number at the ith position.
If the dp state has already been calculated , return it.
If the array is traversed and no element has been selected yet then select the current element.
If the parity of the current and previously selected element are different , then select the current element.
Skip the current element and move to the next element.
Return the result.
Function to calculate the maximum sum subsequence with consecutive terms having different parity.
Initialize the dp [ ] array with - 1.
Initially the prev value is set to say 2 , as the first element can anyways be selected.
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to maximum Sum Subsequence made up of consecutive elements of different parity and the other steps required.
 def maxSum ( arr , i , n , prev , is_selected , dp ) :
	if ( i == n ) :
		return 0
	cur = abs ( arr [ i ] ) % 2
	if ( dp [ i ] [ prev ] != - 1 ) :
		return dp [ i ] [ prev ]
	if ( i == n - 1 and is_selected == 0 ) :
		dp [ i ] [ prev ] = arr [ i ]
		return dp [ i ] [ prev ]
	if ( cur != prev ) :
		dp [ i ] [ prev ] = arr [ i ] + maxSum ( arr , i + 1 , n , cur , 1 , dp )
	dp [ i ] [ prev ] = max ( dp [ i ] [ prev ] , maxSum ( arr , i + 1 , n , prev , is_selected , dp ) )
	return dp [ i ] [ prev ]
def maxSumUtil ( arr , n ) :
	dp = [ [ - 1 for i in range ( 3 ) ] for j in range ( 100 ) ]
	print ( maxSum ( arr , 0 , n , 2 , 0 , dp ) )
if __name__ == ' _ _ main _ _ ' :
	arr = [ 1 , 2 , 6 , 8 , - 5 , 10 ]
	N = len ( arr )
	maxSumUtil ( arr , N )