This problem asks to find the largest even sum of a subsequence of length k
from a given array nums
. The solution uses a greedy approach combined with sorting.
Approach:
Sort: The array nums
is sorted in ascending order. This allows us to easily select the largest k
elements as a starting point for our subsequence.
Initial Sum: The sum of the largest k
elements is calculated. If this sum is already even, it's the answer, and we're done.
Odd Sum Handling: If the initial sum is odd, we need to adjust the subsequence to make the sum even. This is done by considering two possible replacements:
Replace smallest even with largest odd: We find the smallest even number among the largest k
elements and the largest odd number among the remaining n-k
elements. Replacing the smallest even with the largest odd will maintain the subsequence length and make the sum even.
Replace smallest odd with largest even: Similarly, we find the smallest odd number among the largest k
elements and the largest even number among the remaining n-k
elements. Replacing the smallest odd with the largest even will achieve the same result.
Maximum Even Sum: The algorithm compares the initial sum (if even), the sum after the first replacement, and the sum after the second replacement. The largest of these even sums is returned. If none of these scenarios produce an even sum, -1 is returned.
Time Complexity Analysis:
nums
.Therefore, the overall time complexity is dominated by the sorting step, making it O(n log n).
Space Complexity Analysis:
Therefore, the space complexity is O(log n).
Code Examples (Python):
import sys
def largestEvenSum(nums: list[int], k: int) -> int:
nums.sort()
ans = sum(nums[-k:]) # Sum of largest k elements
if ans % 2 == 0:
return ans
n = len(nums)
mx1 = mx2 = -sys.maxsize # Initialize with negative infinity
for x in nums[:n - k]:
if x % 2:
mx1 = max(mx1, x)
else:
mx2 = max(mx2, x)
mi1 = mi2 = sys.maxsize # Initialize with positive infinity
for x in nums[-k:][::-1]: # Iterate in reverse
if x % 2:
mi2 = min(mi2, x)
else:
mi1 = min(mi1, x)
ans = max(ans - mi1 + mx1 if mx1 != -sys.maxsize and mi1 != sys.maxsize else -sys.maxsize,
ans - mi2 + mx2 if mx2 != -sys.maxsize and mi2 != sys.maxsize else -sys.maxsize,
-1)
return ans
This improved Python code handles edge cases more robustly (e.g., when no suitable even or odd numbers are found for replacement) by using sys.maxsize
and explicitly checking for valid replacements. The other language examples follow a similar logic and time/space complexity.