Maximum distance to the nearest person

In a row of seats, 1 represents someone sitting in the seat, 0 represents the seat is empty.

There is at least one empty seat, and at least one person sits in the seat.

I hope to sit on a seat that maximizes the distance between him and the nearest person.

Return to him the greatest distance from the nearest person to him.

Example

Sample 1:

Input: [1, 0, 0, 0, 1, 0, 1]
Output: 2
 Interpretation:
If you sit on second empty seats (seats[2]), the distance between him and the nearest person is 2.
If he sits on any other vacancy, he will be 1 away from the nearest person.
Therefore, the maximum distance from him to the nearest person is 2.

Sample 2:

Input: [1, 0, 0, 0]
Output: 3
 Interpretation: 
If he sits in the last seat, he has 3 seats away from the nearest person.
This is the maximum distance possible, so the answer is 3.

Matters needing attention

  • 1 <= seats.length <= 20000
  • seats contain only 0 and 1, at least one 0, and at least one 1.

How does input test data (one parameter per row) understand test data?

 

class Solution {
public:
    /**
     * @param seats: an array
     * @return: the maximum distance
     */
    int maxDistToClosest(vector<int> &seats) {
        // Write your code here.
        int size = seats.size();
        int ret = INT_MIN;
        vector<int> dp(size);
        fill(dp.begin(), dp.end(), INT_MAX);
        for(int i = 0; i < size; i++)
        {
            if(seats[i] == 1)
                dp[i] = 0;
            else
            {
                for(int j = i-1; j >= 0; j--)
                {
                    if(seats[j] == 1)
                    {
                        dp[i] = dp[i] < abs(i - j) ? dp[i] : abs(i - j);
                        break;
                    }                   
                }
                
                for(int j = i+1; j < size; j++)
                {
                    if(seats[j] == 1)
                    {
                        dp[i] = dp[i] < abs(i - j) ? dp[i] : abs(i - j);
                        break;
                    }                   
                }
                ret = ret > dp[i]  ? ret : dp[i];
            }
            cout<<dp[i]<<endl;
        }
        return ret;
    }
};

 

Posted by xander85 on Mon, 30 Sep 2019 08:51:27 -0700