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
Understanding the Visualization
1
Input
Array [4,1,5,3,1] with k=3
2
Process
Find k elements that give maximum even sum
3
Output
Return 12 (from selecting 4,5,3)
Key Takeaway
🎯 Key Insight: Use greedy selection of largest elements, then adjust parity by smart swapping to ensure an even sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code