|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 849. Maximize Distance to Closest Person |
| 5 | + * |
| 6 | + * In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. |
| 7 | + * There is at least one empty seat, and at least one person sitting. |
| 8 | + * Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. |
| 9 | + * Return that maximum distance to closest person. |
| 10 | + * |
| 11 | + * Example 1: |
| 12 | + * Input: [1,0,0,0,1,0,1] |
| 13 | + * Output: 2 |
| 14 | + * Explanation: |
| 15 | + * If Alex sits in the second open seat (seats[2]), then the closest person has distance 2. |
| 16 | + * If Alex sits in any other open seat, the closest person has distance 1. |
| 17 | + * Thus, the maximum distance to the closest person is 2. |
| 18 | + * |
| 19 | + * Example 2: |
| 20 | + * Input: [1,0,0,0] |
| 21 | + * Output: 3 |
| 22 | + * Explanation: |
| 23 | + * If Alex sits in the last seat, the closest person is 3 seats away. |
| 24 | + * This is the maximum distance possible, so the answer is 3. |
| 25 | + * Note: |
| 26 | + * |
| 27 | + * 1 <= seats.length <= 20000 |
| 28 | + * seats contains only 0s or 1s, at least one 0, and at least one 1. |
| 29 | + * */ |
| 30 | +public class _849 { |
| 31 | + public static class Solution1 { |
| 32 | + int maxDist = 0; |
| 33 | + public int maxDistToClosest(int[] seats) { |
| 34 | + for (int i = 0; i < seats.length; i++) { |
| 35 | + if (seats[i] == 0) { |
| 36 | + extend(seats, i); |
| 37 | + } |
| 38 | + } |
| 39 | + return maxDist; |
| 40 | + } |
| 41 | + |
| 42 | + private void extend(int[] seats, int position) { |
| 43 | + int left = position - 1; |
| 44 | + int right = position + 1; |
| 45 | + int leftMinDistance = 1; |
| 46 | + while (left >= 0) { |
| 47 | + if (seats[left] == 0) { |
| 48 | + leftMinDistance++; |
| 49 | + left--; |
| 50 | + } else { |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + int rightMinDistance = 1; |
| 55 | + while (right < seats.length) { |
| 56 | + if (seats[right] == 0) { |
| 57 | + rightMinDistance++; |
| 58 | + right++; |
| 59 | + } else { |
| 60 | + break; |
| 61 | + } |
| 62 | + } |
| 63 | + int maxReach = 0; |
| 64 | + if (position == 0) { |
| 65 | + maxReach = rightMinDistance; |
| 66 | + } else if (position == seats.length - 1) { |
| 67 | + maxReach = leftMinDistance; |
| 68 | + } else { |
| 69 | + maxReach = Math.min(leftMinDistance, rightMinDistance); |
| 70 | + } |
| 71 | + maxDist = Math.max(maxDist, maxReach); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments