Problem Description
Given an array "team" where 0 represents a person who is not “it” and 1 represents a person who is “it”, and an integer "dist", each person who is “it” can catch at most one person who is not “it” provided that the target’s index is within the range [i - dist, i + dist]. Return the maximum number of people that can be caught.
Key Insights
- Separate the indices of taggers (1’s) and non-taggers (0’s).
- Sorting helps, although the input order already corresponds to indices.
- Use a two-pointer greedy algorithm to pair each tagger with a valid non-tagger in range.
- Increment the pointer for tagger and non-tagger whenever a match is found.
- If the current non-tagger is too far left (before tagger minus dist), move to the next non-tagger.
- If the current non-tagger is too far right (beyond tagger plus dist), move to the next tagger.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the team array. Space Complexity: O(n), due to storing separate lists for indices of taggers and non-taggers.
Solution
The approach is to traverse through the list with two pointers:
- First, create two lists: one for the indices where team[i] is 1 (taggers) and one for where team[i] is 0 (non-taggers).
- Initialize two pointers, one for taggers and one for non-taggers.
- For each tagger, check if the corresponding non-tagger is in the valid range [tagger - dist, tagger + dist].
- If the non-tagger’s index is too small (less than tagger - dist), move the non-tagger pointer.
- If the non-tagger’s index is too large (greater than tagger + dist), move the tagger pointer.
- If the candidate is in range, count the successful tagging and move both pointers. This greedy approach ensures that each tagger catches at most one non-tagger and each non-tagger is caught only once.
Data structures used include arrays (or lists) for storing indices and two pointers for iteration. This greedy matching method is efficient and straightforward.