Maximum Number of People That Can Be Caught in Tag Problem
Description
LeetCode Problem 1989.
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". The people who are "it" want to catch as many people as possible who are not "it".
You are given a 0-indexed integer array team containing only zeros (denoting people who are not "it") and ones (denoting people who are "it"), and an integer dist. 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".
Return the maximum number of people that the people who are "it" can catch.
Example 1:
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.
Example 2:
Input: team = [1], dist = 1
Output: 0
Explanation:
There are no people who are not "it" to catch.
Example 3:
Input: team = [0], dist = 1
Output: 0
Explanation:
There are no people who are "it" to catch people.
Constraints:
1 <= team.length <= 10^50 <= team[i] <= 11 <= dist <= team.length
Solution
Approach: Two Pointers
Greedily, each person who is "it" (going left to right) should catch the leftmost person who is not "it" and is still within reach and not yet caught; that never hurts anyone further right.
Keep a pointer j to the next candidate. For each i with team[i] = 1, move j right while team[j] is "it" or j is more than dist to the left of i. If j is then within dist of i, count a catch and move j one step further.
Complexity: time O(n), space O(1).
class Solution:
def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int:
ans = j = 0
n = len(team)
for i, x in enumerate(team):
if x:
while j < n and (team[j] or i - j > dist):
j += 1
if j < n and abs(i - j) <= dist:
ans += 1
j += 1
return ans