Skip to content

Commit 194b0ff

Browse files
committed
Add solution #849
1 parent fd42b5c commit 194b0ff

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,7 @@
656656
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
657657
847|[Shortest Path Visiting All Nodes](./0847-shortest-path-visiting-all-nodes.js)|Hard|
658658
848|[Shifting Letters](./0848-shifting-letters.js)|Medium|
659+
849|[Maximize Distance to Closest Person](./0849-maximize-distance-to-closest-person.js)|Medium|
659660
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
660661
868|[Binary Gap](./0868-binary-gap.js)|Easy|
661662
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 849. Maximize Distance to Closest Person
3+
* https://leetcode.com/problems/maximize-distance-to-closest-person/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array representing a row of seats where seats[i] = 1 represents a person
7+
* sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
8+
*
9+
* There is at least one empty seat, and at least one person sitting.
10+
*
11+
* Alex wants to sit in the seat such that the distance between him and the closest person to
12+
* him is maximized.
13+
*
14+
* Return that maximum distance to the closest person.
15+
*/
16+
17+
/**
18+
* @param {number[]} seats
19+
* @return {number}
20+
*/
21+
var maxDistToClosest = function(seats) {
22+
let lastOccupied = -1;
23+
let result = 0;
24+
25+
for (let i = 0; i < seats.length; i++) {
26+
if (seats[i] === 1) {
27+
if (lastOccupied === -1) {
28+
result = i;
29+
} else {
30+
result = Math.max(result, Math.floor((i - lastOccupied) / 2));
31+
}
32+
lastOccupied = i;
33+
}
34+
}
35+
36+
if (lastOccupied !== seats.length - 1) {
37+
result = Math.max(result, seats.length - 1 - lastOccupied);
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)