LeetCode 849: Maximize Distance to Closest Person Solution

Master LeetCode problem 849 (Maximize Distance to Closest Person), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

849. Maximize Distance to Closest Person

Medium

Problem Explanation

Explanation:

  • We can solve this problem by iterating through the array and finding the maximum distance between consecutive occupied seats or the start/end of the array and an occupied seat.
  • We calculate the distance by keeping track of the last index of an occupied seat and updating the maximum distance whenever we find a new occupied seat.
  • We handle the edge cases of the first and last seat separately to calculate the distance to the closest person from the start and end respectively.
  • Finally, we return the maximum distance calculated.

Time complexity: O(n) where n is the number of seats
Space complexity: O(1)

Solution Code

class Solution {
    public int maxDistToClosest(int[] seats) {
        int maxDistance = 0;
        int lastOccupied = -1;
        
        for (int i = 0; i < seats.length; i++) {
            if (seats[i] == 1) {
                if (lastOccupied == -1) {
                    maxDistance = i;
                } else {
                    maxDistance = Math.max(maxDistance, (i - lastOccupied) / 2);
                }
                lastOccupied = i;
            }
        }
        
        return Math.max(maxDistance, seats.length - 1 - lastOccupied);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 849 (Maximize Distance to Closest Person)?

This page provides optimized solutions for LeetCode problem 849 (Maximize Distance to Closest Person) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 849 (Maximize Distance to Closest Person)?

The time complexity for LeetCode 849 (Maximize Distance to Closest Person) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 849 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 849 in Java, C++, or Python.

Back to LeetCode Solutions