In this problem, you are given an array of integers and an integer k. You need to find a subsequence of length k such that the sum of its elements is as large as possible AND the sum is an even number. If no such subsequence exists, you should return -1. A subsequence is formed by deleting zero or more elements from the original array while keeping the relative order of the remaining elements.
Companies like Microsoft ask this question to test a candidate's ability to combine sorting with greedy logic. It is more complex than simply picking the k largest elements because those might sum to an odd number. It requires the candidate to identify the "minimal adjustments" needed to turn an odd sum into an even one by swapping elements between odd and even groups. It tests logical reasoning and edge-case handling.
This problem uses a Greedy Approach with Sorting.
k elements.Array: [4, 1, 5, 3, 2], k = 3.
The most common mistake is not considering both swap options (replacing an even with an odd or an odd with an even). Only checking one of these can lead to a sub-optimal or incorrect result. Another mistake is not handling the case where there are no even or odd numbers available for a swap, which would make the swap impossible. Candidates also sometimes forget that the result must be even and might incorrectly return a larger odd sum.
When solving the Subsequence of Size K With the Largest Even Sum interview question, start by picking the k largest numbers greedily. Then, discuss how to fix the parity. This "Greedy then Adjust" strategy is very effective for parity-based problems. Be sure to mention the O(n log n) time complexity due to sorting.