|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=849 lang=java |
| 3 | + * |
| 4 | + * [849] Maximize Distance to Closest Person |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/maximize-distance-to-closest-person/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (42.37%) |
| 10 | + * Likes: 669 |
| 11 | + * Dislikes: 96 |
| 12 | + * Total Accepted: 55.4K |
| 13 | + * Total Submissions: 130.8K |
| 14 | + * Testcase Example: '[1,0,0,0,1,0,1]' |
| 15 | + * |
| 16 | + * In a row of seats, 1 represents a person sitting in that seat, and 0 |
| 17 | + * represents that the seat is empty. |
| 18 | + * |
| 19 | + * There is at least one empty seat, and at least one person sitting. |
| 20 | + * |
| 21 | + * Alex wants to sit in the seat such that the distance between him and the |
| 22 | + * closest person to him is maximized. |
| 23 | + * |
| 24 | + * Return that maximum distance to closest person. |
| 25 | + * |
| 26 | + * |
| 27 | + * Example 1: |
| 28 | + * |
| 29 | + * |
| 30 | + * Input: [1,0,0,0,1,0,1] |
| 31 | + * Output: 2 |
| 32 | + * Explanation: |
| 33 | + * If Alex sits in the second open seat (seats[2]), then the closest person has |
| 34 | + * distance 2. |
| 35 | + * If Alex sits in any other open seat, the closest person has distance 1. |
| 36 | + * Thus, the maximum distance to the closest person is 2. |
| 37 | + * |
| 38 | + * |
| 39 | + * Example 2: |
| 40 | + * |
| 41 | + * |
| 42 | + * Input: [1,0,0,0] |
| 43 | + * Output: 3 |
| 44 | + * Explanation: |
| 45 | + * If Alex sits in the last seat, the closest person is 3 seats away. |
| 46 | + * This is the maximum distance possible, so the answer is 3. |
| 47 | + * |
| 48 | + * |
| 49 | + * Note: |
| 50 | + * |
| 51 | + * |
| 52 | + * 1 <= seats.length <= 20000 |
| 53 | + * seats contains only 0s or 1s, at least one 0, and at least one 1. |
| 54 | + * |
| 55 | + * |
| 56 | + * |
| 57 | + * |
| 58 | + */ |
| 59 | + |
| 60 | +// @lc code=start |
| 61 | +class Solution { |
| 62 | + public int maxDistToClosest(int[] seats) { |
| 63 | + int ans = 0; |
| 64 | + int last = -1; |
| 65 | + for(int i=0; i<seats.length; i++){ |
| 66 | + if(seats[i] == 1){ |
| 67 | + if(last == -1) |
| 68 | + ans = Math.max(ans, i); |
| 69 | + else |
| 70 | + ans = Math.max(ans, (i-last)/2); |
| 71 | + last = i; |
| 72 | + } |
| 73 | + } |
| 74 | + if(last != -1) |
| 75 | + ans = Math.max(ans, seats.length-1 - last); |
| 76 | + return ans; |
| 77 | + } |
| 78 | +} |
| 79 | +// @lc code=end |
0 commit comments