Skip to content

Commit 16ef803

Browse files
committed
Added Maximum Distance to Closest Person
1 parent 85d5677 commit 16ef803

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,8 @@ pub mod keys_and_rooms; // 841 ✓
565565

566566
pub mod backspace_string_compare; // 844 ✓
567567

568+
pub mod maximum_distance_to_closest_person; // 849 ✓
569+
568570
pub mod peak_index_in_a_mountain_array; // 852 ✓
569571
pub mod car_fleet; // 853 ✓
570572

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/// You are given an array representing a row of `seats` where `seats[i] = 1` represents a person
2+
/// sitting in the `ith` seat, and `seats[i] == 0` represents the `ith` seat is empty (0-indexed).
3+
///
4+
/// There is at least one empty seat, and at least one person sitting.
5+
///
6+
/// Alex wants to sit in the seat such that the distance between him and the closest person to him
7+
/// is maximized.
8+
///
9+
/// Return that maximum distance to the closest person.
10+
struct Solution;
11+
12+
impl Solution {
13+
14+
pub fn max_dist_to_closest(seats: Vec<i32>) -> i32 {
15+
let n = seats.len();
16+
17+
let mut result = 0;
18+
let mut last_filled;
19+
20+
let mut i = 0;
21+
loop {
22+
if seats[i] == 1 {
23+
last_filled = i;
24+
if i > 0 {
25+
result = i;
26+
}
27+
break;
28+
}
29+
i += 1;
30+
}
31+
32+
for j in i..n {
33+
if seats[j] == 1 {
34+
let diff = (j - last_filled) / 2;
35+
if diff > result {
36+
result = diff;
37+
}
38+
last_filled = j;
39+
}
40+
}
41+
42+
if seats[n-1] == 0 {
43+
let diff = n-1 - last_filled;
44+
if diff > result {
45+
result = diff;
46+
}
47+
}
48+
49+
result as i32
50+
}
51+
52+
}
53+
54+
#[cfg(test)]
55+
mod tests {
56+
use super::Solution;
57+
58+
#[test]
59+
fn example_1() {
60+
let seats = vec![1,0,0,0,1,0,1];
61+
let result = Solution::max_dist_to_closest(seats);
62+
assert_eq!(result, 2);
63+
}
64+
65+
#[test]
66+
fn example_2() {
67+
let seats = vec![1,0,0,0];
68+
let result = Solution::max_dist_to_closest(seats);
69+
assert_eq!(result, 3);
70+
}
71+
72+
#[test]
73+
fn example_3() {
74+
let seats = vec![0,1];
75+
let result = Solution::max_dist_to_closest(seats);
76+
assert_eq!(result, 1);
77+
}
78+
79+
#[test]
80+
fn example_4() {
81+
let seats = vec![0,0,0,1,0,1,0];
82+
let result = Solution::max_dist_to_closest(seats);
83+
assert_eq!(result, 3);
84+
}
85+
86+
#[test]
87+
fn example_5() {
88+
let seats = vec![0,1,0,0,0,0,0,0,1,0,0,1];
89+
let result = Solution::max_dist_to_closest(seats);
90+
assert_eq!(result, 3);
91+
}
92+
93+
}

0 commit comments

Comments
 (0)