Skip to content

2098. Subsequence of Size K With the Largest Even Sum 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
 public:
  long long largestEvenSum(vector<int>& nums, int k) {
    ranges::sort(nums);
    long sum = accumulate(nums.end() - k, nums.end(), 0L);
    if (sum % 2 == 0)
      return sum;

    int minOdd = -1;
    int minEven = -1;
    int maxOdd = -1;
    int maxEven = -1;

    for (int i = nums.size() - 1; i + k >= nums.size(); --i)
      if (nums[i] % 2 == 1)
        minOdd = nums[i];
      else
        minEven = nums[i];

    for (int i = 0; i + k < nums.size(); ++i)
      if (nums[i] % 2 == 1)
        maxOdd = nums[i];
      else
        maxEven = nums[i];

    long ans = -1;

    if (maxEven >= 0 && minOdd >= 0)
      ans = max(ans, sum + maxEven - minOdd);
    if (maxOdd >= 0 && minEven >= 0)
      ans = max(ans, sum + maxOdd - minEven);
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
  public long largestEvenSum(int[] nums, int k) {
    Arrays.sort(nums);

    long sum = 0;
    int minOdd = -1;
    int minEven = -1;
    int maxOdd = -1;
    int maxEven = -1;

    for (int i = nums.length - 1; i + k >= nums.length; --i) {
      sum += nums[i];
      if (nums[i] % 2 == 1)
        minOdd = nums[i];
      else
        minEven = nums[i];
    }

    if (sum % 2 == 0)
      return sum;

    for (int i = 0; i + k < nums.length; ++i)
      if (nums[i] % 2 == 1)
        maxOdd = nums[i];
      else
        maxEven = nums[i];

    long ans = -1;

    if (maxEven >= 0 && minOdd >= 0)
      ans = Math.max(ans, sum + maxEven - minOdd);
    if (maxOdd >= 0 && minEven >= 0)
      ans = Math.max(ans, sum + maxOdd - minEven);
    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
  def largestEvenSum(self, nums: list[int], k: int) -> int:
    nums.sort()
    summ = sum(nums[-k:])
    if summ % 2 == 0:
      return summ

    minOdd = -1
    minEven = -1
    maxOdd = -1
    maxEven = -1

    for i in range(len(nums) - 1, len(nums) - k - 1, -1):
      if nums[i] & 1:
        minOdd = nums[i]
      else:
        minEven = nums[i]

    for i in range(len(nums) - k):
      if nums[i] & 1:
        maxOdd = nums[i]
      else:
        maxEven = nums[i]

    ans = -1

    if maxEven >= 0 and minOdd >= 0:
      ans = max(ans, summ + maxEven - minOdd)
    if maxOdd >= 0 and minEven >= 0:
      ans = max(ans, summ + maxOdd - minEven)
    return ans