Maximum Number of People That Can Be Caught in Tag - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: team = [0,1,0,1,0], dist = 1
Output: 2
💡 Note: Guard at position 1 can catch person at position 0 or 2. Guard at position 3 can catch person at position 2 or 4. Using greedy strategy: guard 1 catches position 2, guard 3 catches position 4. Total: 2 catches.
Example 2 — Overlapping Ranges
$ Input: team = [1,0,0,0,1], dist = 2
Output: 3
💡 Note: Guard at position 0 can catch positions 1 or 2. Guard at position 4 can catch positions 2 or 3. Guard 0 catches position 2 (rightmost), guard 4 catches position 3, and position 1 remains. Actually, guard 0 should catch position 1, guard 4 catches positions 2,3. Total: 3 catches.
Example 3 — Single Guard
$ Input: team = [1,0,0], dist = 1
Output: 1
💡 Note: Only one guard at position 0. Can catch person at position 1 within range [0,1]. Total: 1 catch.

Constraints

  • 1 ≤ team.length ≤ 105
  • team[i] is either 0 or 1
  • 1 ≤ dist ≤ 105

Visualization

Tap to expand
Maximum Number of People Caught in Tag INPUT team array: 0 idx:0 1 idx:1 0 idx:2 1 idx:3 0 idx:4 Legend: = "it" (catchers) = not "it" (runners) Parameters: team = [0,1,0,1,0] dist = 1 (catch range: i-1 to i+1) ALGORITHM STEPS 1 Two Pointers Setup i=0 (runners), j=0 (catchers) 2 Greedy Matching Match nearest runner to catcher Match 1: 1 i=1 0 i=0 CAUGHT! Match 2: 1 i=3 0 i=4 CAUGHT! 3 Check Distance |i - j| must be <= dist 4 Count Matches Increment count for each catch FINAL RESULT Final State: CAUGHT USED FREE USED CAUGHT Output: 2 OK - Maximum Catches 2 people were caught! Key Insight: Greedy two-pointer approach: Sort positions of catchers and runners separately. Match each catcher with the nearest available runner within distance. Move pointers left-to-right to ensure optimal pairing. Time: O(n), Space: O(n) for storing positions. TutorialsPoint - Maximum Number of People That Can Be Caught in Tag | Greedy Assignment
Asked in
Google 15 Facebook 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen