Subsequence of Size K With the Largest Even Sum — LeetCode 2098 Python Solution
MediumLeetCode PremiumGreedyArraySorting
- Problem
- #2098
- Pattern
- Greedy
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [4,1,5,3,1], k = 3
- Output
- 12
- Explanation
- The subsequence with the largest possible even sum is [4,5,3]. It has a sum of 4 + 5 + 3 = 12.
Python solution
Python
class Solution:
def largestEvenSum(self, nums: List[int], k: int) -> int:
nums.sort()
ans = sum(nums[-k:])
if ans % 2 == 0:
return ans
n = len(nums)
mx1 = mx2 = -inf
for x in nums[: n - k]:
if x & 1:
mx1 = x
else:
mx2 = x
mi1 = mi2 = inf
for x in nums[-k:][::-1]:
if x & 1:
mi2 = x
else:
mi1 = x
ans = max(ans - mi1 + mx1, ans - mi2 + mx2, -1)
return -1 if ans < 0 else ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2098. Subsequence of Size K With the Largest Even Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2098. Subsequence of Size K With the Largest Even Sum?
- LeetCode 2098. Subsequence of Size K With the Largest Even Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2098. Subsequence of Size K With the Largest Even Sum?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2098. Subsequence of Size K With the Largest Even Sum?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2098. Subsequence of Size K With the Largest Even Sum cover?
- LeetCode 2098. Subsequence of Size K With the Largest Even Sum is tagged Greedy, Array and Sorting on LeetCode.
- Is LeetCode 2098. Subsequence of Size K With the Largest Even Sum a premium problem?
- Yes. LeetCode 2098. Subsequence of Size K With the Largest Even Sum is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.