human
Maximum even sum subsequence of length K | Function to find the maximum even sum of any subsequence of length K.
If count of elements is less than K.
Stores maximum even subsequence sum.
Stores Even numbers.
Stores Odd numbers.
Traverse the array.
If current element is an odd number.
Insert odd number.
Insert even numbers.
Sort Odd [ ] array.
Sort Even [ ] array.
Stores current index Of Even [ ] array.
Stores current index Of Odd [ ] array.
If K is odd.
If count of elements in Even [ ] >= 1.
Update maxSum.
Update i.
If count of elements in Even [ ] array is 0..
Update K.
If count of elements in Even [ ] and odd [ ] >= 2.
Update maxSum.
Update j ..
Update maxSum.
Update i.
Update K.
If count of elements in Even [ ] array >= 2..
Update maxSum.
Update i ..
Update K ..
If count of elements in Odd [ ] array >= 2.
Update maxSum.
Update i ..
Update K ..
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to maximum even sum subsequence of length K and the other steps required.
 def evenSumK ( arr , N , K ) :
	if ( K > N ) :
		return - 1
	maxSum = 0
	Even = [ ]
	Odd = [ ]
	for i in range ( N ) :
		if ( arr [ i ] % 2 ) :
			Odd . append ( arr [ i ] )
		else :
			Even . append ( arr [ i ] )
	Odd . sort ( reverse = False )
	Even . sort ( reverse = False )
	i = len ( Even ) - 1
	j = len ( Odd ) - 1
	while ( K > 0 ) :
		if ( K % 2 == 1 ) :
			if ( i >= 0 ) :
				maxSum += Even [ i ]
				i -= 1
			else :
				return - 1
			K -= 1
		elif ( i >= 1 and j >= 1 ) :
			if ( Even [ i ] + Even [ i - 1 ] <= Odd [ j ] + Odd [ j - 1 ] ) :
				maxSum += Odd [ j ] + Odd [ j - 1 ]
				j -= 2
			else :
				maxSum += Even [ i ] + Even [ i - 1 ]
				i -= 2
			K -= 2
		elif ( i >= 1 ) :
			maxSum += Even [ i ] + Even [ i - 1 ]
			i -= 2
			K -= 2
		elif ( j >= 1 ) :
			maxSum += Odd [ j ] + Odd [ j - 1 ]
			j -= 2
			K -= 2
	return maxSum
if __name__ == ' _ _ main _ _ ' :
	arr = [ 2 , 4 , 10 , 3 , 5 ]
	N = len ( arr )
	K = 3
	print ( evenSumK ( arr , N , K ) )