How to Solve the Maximize Distance to Closest Person Challenge in Java

  • Home /
  • Blog Posts /
  • How to Solve the Maximize Distance to Closest Person Challenge in Java

The challenge

You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the i<sup>th</sup> seat, and seats[i] = 0 represents that the i<sup>th</sup> seat is empty (0-indexed).

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. 

Return that maximum distance to the closest person.

Example 1:

Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation: 
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

Example 2:

Input: seats = [1,0,0,0]
Output: 3
Explanation: 
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

Example 3:

Input: seats = [0,1]
Output: 1

Constraints:

  • 2 <= seats.length <= 2 * 10<sup>4</sup>
  • seats[i] is `` or 1.
  • At least one seat is empty.
  • At least one seat is occupied.

The solution in Java code

public class MaximizeDistancetoClosestPerson {
    public int maxDistToClosest(int[] seats) {
        int maxSpace = -1;
        int alex = 0;
        for(int i=0;i<seats.length;i++){
            int start = i;
            while(i+1<seats.length && seats[i]+seats[i+1]==0){
                i++;
            }
            if(maxSpace<=i-start){
                if(i==seats.length-1 || start==0) alex = i-start+1;
                else alex = (i-start)/2 +1;
                maxSpace = Math.max(maxSpace,alex);
            }
        }
        return maxSpace;
    }
}

Test cases to validate our Java solution

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class MaximizeDistancetoClosestPersonTest {

    @Test
    void maxDistToClosest_case1() {
        int actual = new MaximizeDistancetoClosestPerson().maxDistToClosest(new int[]{1,0,0,0,1,0,1});
        assertEquals(2, actual);
    }

    @Test
    void maxDistToClosest_case2() {
        int actual = new MaximizeDistancetoClosestPerson().maxDistToClosest(new int[]{1,0,0,0});
        assertEquals(3, actual);
    }

    @Test
    void maxDistToClosest_case3() {
        int actual = new MaximizeDistancetoClosestPerson().maxDistToClosest(new int[]{0,1});
        assertEquals(1, actual);
    }
}