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 themaximum number of people that the people who are “it” can catch.
Input: team =[0,1,0,1,0], dist =3Output: 2Explanation:
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:
1
2
3
4
Input: team =[1], dist =1Output: 0Explanation:
There are no people who are not "it" to catch.
Example 3:
1
2
3
Input: team =[0], dist =1Output: 0Explanation: There are no people who are "it" to catch people.
To maximize the number of people caught, match each person who is “it” to the nearest available person who is not “it” within the allowed distance. Use two pointers to efficiently pair “it” and “not it” people.
classSolution {
funcatchMaximumPeople(team: IntArray, dist: Int): Int {
val its = mutableListOf<Int>()
val notits = mutableListOf<Int>()
for (i in team.indices) {
if (team[i] ==1) its.add(i) else notits.add(i)
}
var ans = 0var i = 0var j = 0while (i < its.size && j < notits.size) {
if (kotlin.math.abs(its[i] - notits[j]) <= dist) {
ans++ i++ j++ } elseif (its[i] < notits[j]) {
i++ } else {
j++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defcatchMaximumPeople(self, team: list[int], dist: int) -> int:
its = [i for i, v in enumerate(team) if v ==1]
notits = [i for i, v in enumerate(team) if v ==0]
ans = i = j =0while i < len(its) and j < len(notits):
if abs(its[i] - notits[j]) <= dist:
ans +=1 i +=1 j +=1elif its[i] < notits[j]:
i +=1else:
j +=1return ans