# 1989. Maximum Number of People That Can Be Caught in Tag

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution { public: int catchMaximumAmountofPeople(vector& team, int dist) { int ans = 0; int i = 0; // 0's index int j = 0; // 1's index while (i < team.size() && j < team.size()) if (i + dist < j || team[i] != 0) { // Find the next 0 that can be caught by 1. ++i; } else if (j + dist < i || team[j] != 1) { // Find the next 1 that can catch 0. ++j; } else { // team[j] catches team[i], so move both. ++ans; ++i; ++j; } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public int catchMaximumAmountofPeople(int[] team, int dist) { int ans = 0; int i = 0; // 0's index int j = 0; // 1's index while (i < team.length && j < team.length) if (i + dist < j || team[i] != 0) { // Find the next 0 that can be caught by 1. ++i; } else if (j + dist < i || team[j] != 1) { // Find the next 1 that can catch 0. ++j; } else { // team[j] catches team[i], so move both. ++ans; ++i; ++j; } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution: def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int: ans = 0 i = 0 # 0's index j = 0 # 1's index while i < len(team) and j < len(team): if i + dist < j or team[i] != 0: # Find the next 0 that can be caught by 1. i += 1 elif j + dist < i or team[j] != 1: # Find the next 1 that can catch 0. j += 1 else: # team[j] catches team[i], so move both. ans += 1 i += 1 j += 1 return ans