Subsequence of Size K With the Largest Even Sum Problem
Description
LeetCode Problem 2098.
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.
Example 1:
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.
Example 2:
Input: nums = [4,6,2], k = 3
Output: 12
Explanation:
The subsequence with the largest possible even sum is [4,6,2]. It has a sum of 4 + 6 + 2 = 12.
Example 3:
Input: nums = [1,3,5], k = 1
Output: -1
Explanation:
No subsequence of nums with length 1 has an even sum.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^51 <= k <= nums.length
Solution
Approach: Greedy + Sorting
Sort the array and take the k largest numbers. If their sum is even, that is the answer.
If the sum is odd, we must change the parity with one swap between the chosen numbers and the n - k unchosen ones:
- Replace the smallest even chosen number with the largest odd unchosen number.
- Replace the smallest odd chosen number with the largest even unchosen number.
Either swap, when it is possible, makes the sum even. Take the larger of the two results; if neither swap exists, return -1.
Complexity: O(n log n) time for the sort, O(log n) extra space.
from math import inf
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 ans