Mid/Senior
Subsequence of Size K With the Largest Even Sum
Given an integer array nums and an integer k, choose a subsequence of nums of size exactly k.
Return the largest possible even sum of such a subsequence. If there is no subsequence of size k with an even sum, return -1.
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.
Example 1
Input
nums = [4,1,5,3,1], k = 3Output
12Choosing the subsequence [4, 5, 3] gives a sum of 12, which is the largest even sum among all subsequences of size 3.
Example 2
Input
nums = [1,3,5], k = 1Output
-1The only subsequences of size 1 are odd numbers, so no even sum is possible.
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
- 1 <= k <= nums.length