Given an array of integers nums that can include negative numbers, find the maximum possible even sum obtainable by selecting any subset of elements.
A subset can be any selection of zero or more elements from the array. The sum of the empty subset is 0, which is even.
Return the maximum even sum achievable. If no non-empty subset yields an even sum greater than 0, return 0.
Function Signature
def max_even_sum(nums: list[int]) -> int:
...
Rules
-
A subset picks elements by position, so equal values at different indices can both be chosen.
-
The chosen elements do not need to be adjacent, and their order does not matter.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [4, -1, 3, 2, 5]
Output: 14
All positive numbers sum to 4 + 3 + 2 + 5 = 14, which is even. No subset can have a larger sum, so the answer is 14.
Input: nums = [1, 3, 5]
Output: 8
All positive numbers sum to 1 + 3 + 5 = 9, which is odd. Removing the smallest odd positive (1) gives 8, which is even. Removing 3 or 5 instead gives 6 or 4.
Input: nums = [7, -1, 2]
Output: 8
The positives sum to 9. Dropping the 7 leaves only 2, while adding the -1 gives 7 - 1 + 2 = 8, the best even total.