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
Inputnums = [4,1,5,3,1], k = 3
Output12
Choosing the subsequence [4, 5, 3] gives a sum of 12, which is the largest even sum among all subsequences of size 3.
Example 2
Inputnums = [1,3,5], k = 1
Output-1
The 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

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate