Approach
Sorting and greedy selection
For Subsequence of Size K With the Largest Even Sum, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 35 lines of C++ from the credited upstream file 2098.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long largestEvenSum(vector<int>& nums, int k) {4 ranges::sort(nums);5 long sum = accumulate(nums.end() - k, nums.end(), 0L);6 if (sum % 2 == 0)7 return sum;8 9 int minOdd = -1;10 int minEven = -1;11 int maxOdd = -1;12 int maxEven = -1;13 14 for (int i = nums.size() - 1; i + k >= nums.size(); --i)15 if (nums[i] % 2 == 1)16 minOdd = nums[i];17 else18 minEven = nums[i];19 20 for (int i = 0; i + k < nums.size(); ++i)21 if (nums[i] % 2 == 1)22 maxOdd = nums[i];23 else24 maxEven = nums[i];25 26 long ans = -1;27 28 if (maxEven >= 0 && minOdd >= 0)29 ans = max(ans, sum + maxEven - minOdd);30 if (maxOdd >= 0 && minEven >= 0)31 ans = max(ans, sum + maxOdd - minEven);32 return ans;33 }34};35