Subsequence of Size K With the Largest Even Sum - Problem

You are given an integer array nums and an integer k. Find the largest even sum of any subsequence of nums that has a length of k.

Return this sum, or -1 if such a sum does not exist.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,1,5,3,1], k = 3
Output: 12
💡 Note: Select [4,5,3] which gives sum = 12 (even). This is the largest possible even sum for k=3 elements.
Example 2 — Need Adjustment
$ Input: nums = [4,1,5,3,1], k = 1
Output: 4
💡 Note: Select [4] which gives sum = 4 (even). The largest single element that gives an even sum.
Example 3 — No Even Sum Possible
$ Input: nums = [1,3,5], k = 3
Output: -1
💡 Note: All elements are odd, so any subsequence of size 3 will have an odd sum (odd+odd+odd=odd).

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Subsequence of Size K With the Largest Even Sum INPUT nums = [4, 1, 5, 3, 1] 4 even 1 odd 5 odd 3 odd 1 odd k = 3 n = 5 Separated & Sorted: Evens: 4 Odds: 5 3 1 1 (descending order) ALGORITHM STEPS 1 Sort & Separate Split into evens/odds, sort descending 2 Pick Top K Elements Greedily select k largest: [5, 4, 3] = 12 3 Check Parity Sum=12 is EVEN OK - Valid! 4 Adjust if Odd Sum If sum is odd, swap: smallest odd in k with largest even outside, or vice versa Selected: 5 + 4 + 3 = 12 (even sum) FINAL RESULT Optimal Subsequence: 5 4 3 + + 5 + 4 + 3 = 12 Output: 12 OK - Largest Even Sum! Verification: Length = 3 (k=3) OK 12 mod 2 = 0 (even) OK Key Insight: To get the largest even sum, first greedily pick the k largest elements. If the sum is already even, we're done. If odd, swap the smallest odd in our selection with the largest even outside (or vice versa) to make sum even while minimizing the loss. This greedy approach with even/odd adjustment guarantees the optimal solution in O(n log n). TutorialsPoint - Subsequence of Size K With the Largest Even Sum | Greedy with Even/Odd Adjustment
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
32.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen