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 >= 1 ; Update maxSum ; Update i . ; Update K . ; Driver Code
function evenSumK ( arr , N , K ) { if ( K > N ) { return - 1 ; } var maxSum = 0 ; var Even = [ ] ; var Odd = [ ] ; for ( var i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 ) { Odd . push ( arr [ i ] ) ; } else { Even . push ( arr [ i ] ) ; } } Odd . sort ( ( a , b ) => a - b ) ; Even . sort ( ( a , b ) => a - b ) ; var i = Even . length - 1 ; var j = Odd . length - 1 ; while ( K > 0 ) { if ( K % 2 == 1 ) { if ( i >= 0 ) { maxSum += Even [ i ] ; i -- ; } else { return - 1 ; } K -- ; } else if ( i >= 1 && 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 ; } else if ( i >= 1 ) { maxSum += Even [ i ] + Even [ i - 1 ] ; i -= 2 ; K -= 2 ; } else if ( j >= 1 ) { maxSum += Odd [ j ] + Odd [ j - 1 ] ; j -= 2 ; K -= 2 ; } } return maxSum ; } var arr = [ 2 , 4 , 10 , 3 , 5 ] ; var N = arr . length ; var K = 3 ; document . write ( evenSumK ( arr , N , K ) ) ;