04
Resource assignment (Greedy Sub-pattern)
Match items from two lists (needs and resources). Give each need the smallest resource that satisfies it, so bigger resources stay free for bigger needs.
Signals in the problem statement
- ›
"each child gets at most one cookie"
- ›
"match players to trainers"
- ›
"permute A to beat B in as many positions as possible"
What makes it different
Count matches → sort both, two pointers. Maximise wins against a fixed order → beat each opponent with the smallest winner, and when you can't win, sacrifice your smallest.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Assign CookiesWalkthroughEasyBasic Anchor·LeetCode #455
- 2Maximum Matching of Players With TrainersWalkthroughMediumBasic Reinforcement·LeetCode #2410
- 3Advantage ShuffleWalkthroughMediumSlight Variation·LeetCode #870
Template
assignment-template.cpp
// Each need gets the smallest resource that satisfies it; count the matches.
int matchSmallestFit(vector<int> need, vector<int> res) {
sort(need.begin(), need.end());
sort(res.begin(), res.end());
int i = 0, j = 0;
while (i < (int)need.size() && j < (int)res.size()) {
if (res[j] >= need[i]) i++; // match: this need is served
j++; // too small now = too small for all later needs
}
return i;
}
// Beat b[] in as many positions as possible by permuting a[] (Tian Ji):
// strongest opponent first; win with our strongest, or sacrifice our weakest.
vector<int> advantage(vector<int> a, const vector<int>& b) {
int n = a.size();
sort(a.begin(), a.end());
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int x, int y) { return b[x] > b[y]; });
vector<int> res(n);
int lo = 0, hi = n - 1;
for (int k : order) res[k] = a[hi] > b[k] ? a[hi--] : a[lo++];
return res;
}Remember this · Greedy
Trigger
Maximise count / minimise cost with a natural "best next step", sorting makes the choice obvious, reachability.
Think
Is there a choice I can always make safely without looking ahead?
Key question
Why can't the greedy choice be worse than the optimal one? (Try to break it with a small example.)