Skip to content

Commit cd094a4

Browse files
committed
Add problem 849: Maximize Distance to Closest Person
1 parent 7b19ab1 commit cd094a4

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,7 @@ pub mod problem_0844_backspace_string_compare;
693693
pub mod problem_0845_longest_mountain_in_array;
694694
pub mod problem_0846_hand_of_straights;
695695
pub mod problem_0848_shifting_letters;
696+
pub mod problem_0849_maximize_distance_to_closest_person;
696697
pub mod problem_0867_transpose_matrix;
697698
pub mod problem_1143_longest_common_subsequence;
698699
pub mod problem_1192_critical_connections_in_a_network;
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn max_dist_to_closest(seats: Vec<i32>) -> i32 {
7+
let i = seats.iter().position(|&x| x != 0).unwrap();
8+
let mut iter = seats[i + 1..].iter().map(|&x| x != 0);
9+
let mut result = i as i32;
10+
11+
loop {
12+
loop {
13+
if let Some(value) = iter.next() {
14+
if !value {
15+
break;
16+
}
17+
} else {
18+
return result;
19+
}
20+
}
21+
22+
let mut length = 1;
23+
24+
loop {
25+
if let Some(value) = iter.next() {
26+
if value {
27+
result = result.max((length + 1) / 2);
28+
29+
break;
30+
}
31+
32+
length += 1;
33+
} else {
34+
return result.max(length);
35+
}
36+
}
37+
}
38+
}
39+
}
40+
41+
// ------------------------------------------------------ snip ------------------------------------------------------ //
42+
43+
impl super::Solution for Solution {
44+
fn max_dist_to_closest(seats: Vec<i32>) -> i32 {
45+
Self::max_dist_to_closest(seats)
46+
}
47+
}
48+
49+
#[cfg(test)]
50+
mod tests {
51+
#[test]
52+
fn test_solution() {
53+
super::super::tests::run::<super::Solution>();
54+
}
55+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn max_dist_to_closest(seats: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(&[1, 0, 0, 0, 1, 0, 1] as &[_], 2),
14+
(&[1, 0, 0, 0], 3),
15+
(&[0, 1], 1),
16+
(&[1, 1, 0, 1, 1], 1),
17+
];
18+
19+
for (seats, expected) in test_cases {
20+
assert_eq!(S::max_dist_to_closest(seats.to_vec()), expected);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)