Wednesday, March 3, 2021

[Google Question][LeetCode] Maximize Distance to Closest Person

Problem: You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith 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:

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.
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.
Input: seats = [0,1]
Output: 1


Approach: if there is only one seat occupied then the result is just the max of occupied_seat_index - 0 and n - 1 - occupied_seat_index. When there are two or more occupied seats then for every pair of occupied_seat_index say (left, right}, it is obvious that maximum distance will be min of left - mid and right - mid.

We can take the maximum of all the maximum distances of all pairs and that will be our result.  


Implementation in C#:

    public int MaxDistToClosest(int[] seats) 

    {    

        int left = this.NextOccupiedSeat(seats);

        int maxDistance = left - 0;

        int right = this.NextOccupiedSeat(seats, left + 1);

        while (right < seats.Length)

        {

            int mid = (left + right) / 2;

            maxDistance = Math.Max(maxDistance, Math.Min(mid - left, right - mid));

            left = right;

            right = this.NextOccupiedSeat(seats, left + 1);

        }

        return Math.Max(maxDistance, seats.Length - 1 - left);

    }

    

    private int NextOccupiedSeat(int[] seats, int start = 0)

    {

        int i = start;

        for (; i < seats.Length; ++i)

        {

            if (seats[i] == 1)

            {

                break;

            }

        }

        return i;

    }


Complexity: O(n)

No comments:

Post a Comment