Approach
Sorting and greedy selection
For Maximize Points After Choosing K Tasks, 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
- 39 lines of C++ from the credited upstream file maximize-points-after-choosing-k-tasks.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.
123 45class Solution {6public:7 long long maxPoints(vector<int>& technique1, vector<int>& technique2, int k) {8 vector<int> idxs(size(technique1));9 iota(begin(idxs), end(idxs), 0);10 nth_element(begin(idxs), begin(idxs) + (k - 1), end(idxs), [&](const auto& a, const auto& b) {11 return technique1[a] - technique2[a] > technique1[b] - technique2[b];12 });13 int64_t result = 0;14 for (int i = 0; i < size(technique1); ++i) {15 result += i < k ? technique1[idxs[i]] : max(technique1[idxs[i]], technique2[idxs[i]]);16 }17 return result;18 }19};20 21222324class Solution2 {25public:26 long long maxPoints(vector<int>& technique1, vector<int>& technique2, int k) {27 vector<int> idxs(size(technique1));28 iota(begin(idxs), end(idxs), 0);29 sort(begin(idxs), end(idxs), [&](const auto& a, const auto& b) {30 return technique1[a] - technique2[a] > technique1[b] - technique2[b];31 });32 int64_t result = 0;33 for (int i = 0; i < size(technique1); ++i) {34 result += i < k ? technique1[idxs[i]] : max(technique1[idxs[i]], technique2[idxs[i]]);35 }36 return result;37 }38};39