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
def evenSumK ( arr , N , K ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxSum = 0 NEW_LINE Even = [ ] NEW_LINE Odd = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT Odd . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT Even . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT Odd . sort ( reverse = False ) NEW_LINE Even . sort ( reverse = False ) NEW_LINE i = len ( Even ) - 1 NEW_LINE j = len ( Odd ) - 1 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT if ( K % 2 == 1 ) : NEW_LINE INDENT if ( i >= 0 ) : NEW_LINE INDENT maxSum += Even [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT K -= 1 NEW_LINE DEDENT elif ( i >= 1 and j >= 1 ) : NEW_LINE INDENT if ( Even [ i ] + Even [ i - 1 ] <= Odd [ j ] + Odd [ j - 1 ] ) : NEW_LINE INDENT maxSum += Odd [ j ] + Odd [ j - 1 ] NEW_LINE j -= 2 NEW_LINE DEDENT else : NEW_LINE INDENT maxSum += Even [ i ] + Even [ i - 1 ] NEW_LINE i -= 2 NEW_LINE DEDENT K -= 2 NEW_LINE DEDENT elif ( i >= 1 ) : NEW_LINE INDENT maxSum += Even [ i ] + Even [ i - 1 ] NEW_LINE i -= 2 NEW_LINE K -= 2 NEW_LINE DEDENT elif ( j >= 1 ) : NEW_LINE INDENT maxSum += Odd [ j ] + Odd [ j - 1 ] NEW_LINE j -= 2 NEW_LINE K -= 2 NEW_LINE DEDENT DEDENT return maxSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 10 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( evenSumK ( arr , N , K ) ) NEW_LINE DEDENT