Show problems as
Classic problem #849MediumArray

Maximize Distance to Closest Person

Real-world version: Farthest Free Locker
Tracked in this browser only
Read Maximize Distance to Closest Person on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A gym corridor has one row of lockers. lockers[i] is 1 when locker i is already assigned to somebody and 0 when it is free. At least one locker is free and at least one is assigned.

You get to claim one free locker. The quiet score of a locker is the number of doors between it and the closest assigned locker, that is |i - j| for the closest index j with lockers[j] == 1.

Return the largest quiet score you can claim.

Examples

Example 1

Input
lockers = [1, 0, 0, 0, 0, 1, 0, 1]
Output
2

Claiming locker 2 puts two doors between it and locker 0, and two doors between it and locker 5.

Example 2

Input
lockers = [0, 0, 0, 1]
Output
3

Claiming locker 0 puts three doors between it and locker 3, the only assigned one.

Example 3

Input
lockers = [1, 0, 0]
Output
2

Claiming locker 2 puts two doors between it and locker 0.

Example 4

Input
lockers = [1, 0, 1, 0, 1]
Output
1

Both free lockers sit next to an assigned locker on either side.

Constraints

  • 2 <= lockers.length <= 2 * 10^4
  • lockers[i] is 0 or 1.
  • At least one locker is free.
  • At least one locker is assigned.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_dist_to_closest(lockers: list[int]) -> int:
Java
public int maxDistToClosest(int[] lockers)