![]() |
VOOZH | about |
You are playing a game of tag with your friends. In tag, people are divided into two teams: people who are “it”, and people who are not “it”. Given an array of 0s and 1s, where 0s are people not "it" and 1s are people who are "it". A person who is "it" at index i can catch any one person whose index is in the range [i - dist, i + dist] (inclusive) and is not "it". The task is to find maximum number of people that the people who are "it" can catch.
Example:
Input: team = {0,1,0,1,0}, dist = 3
Output: 2
Explanation:
- The person who is "it" at index 1 can catch people in the range [i-dist, i+dist] = [1-3, 1+3] = [-2, 4].
- They can catch the person who is not "it" at index 2.
- The person who is "it" at index 3 can catch people in the range [i-dist, i+dist] = [3-3, 3+3] = [0, 6].
- They can catch the person who is not "it" at index 0.
- The person who is not "it" at index 4 will not be caught because the people at indices 1 and 3 are already catching one person but the answer should be 3.
Input: team = {1}, dist = 1
Output: 0
Explanation: There are no people who are not "it" to catch.
Approach:
1. If we count the number of 1s and 0s in given team as ones and zeros, the answer cannot exceed ones, since each person "it" can catch at most 1 other person.
For example:
- team = [0,1,1,1], dist = 1 -> answer = 1
- team = [1,0,0,1,0,1], dist = 1 -> answer = 3
2. When there are reachable 0s for a person, we want to catch as far left as possible. So as to maximize opportunity for 1s to its rightside.
For example:
- team = [0,1,0,1] dist = 1
- if team[1] catch team[2], team[3] won't be able to catch any person.
- if team[1] catch team[0], team[3] can catch team[2] [1,0,0,0,1,1] dist = 2
- if team[0] catch team[2], team[4] can only catch team[3], and answer is 2.
3. Apply two pointers. Whenever we meet 1, scan reachable range, following previous position after the 0, for the first 0.
Steps-by-step approach:
Below is the implementation of the above approach:
The maximum number of people that can be caught is 4.
Time Complexity: O(n)
Auxiliary Space: O(1)