Skip to content

Commit 978e4d1

Browse files
committed
Add problem 3386: Button with Longest Push Time
1 parent 0abc45c commit 978e4d1

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2211,6 +2211,7 @@ pub mod problem_3375_minimum_operations_to_make_array_values_equal_to_k;
22112211
pub mod problem_3376_minimum_time_to_break_locks_i;
22122212
pub mod problem_3379_transformed_array;
22132213
pub mod problem_3381_maximum_subarray_sum_with_length_divisible_by_k;
2214+
pub mod problem_3386_button_with_longest_push_time;
22142215

22152216
#[cfg(test)]
22162217
mod test_utilities;
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::cmp::Ordering;
6+
7+
impl Solution {
8+
pub fn button_with_longest_time(events: Vec<Vec<i32>>) -> i32 {
9+
let mut max_index = 0;
10+
let mut max_duration = 0;
11+
let mut prev_index = 0;
12+
let mut prev_time = 0;
13+
14+
events
15+
.iter()
16+
.filter_map(|event| <[i32; 2]>::try_from(event.as_slice()).ok())
17+
.map(|event| event.map(i32::cast_unsigned))
18+
.for_each(|[index, time]| {
19+
let duration = time - prev_time;
20+
21+
match duration.cmp(&max_duration) {
22+
Ordering::Less => {}
23+
Ordering::Equal => {
24+
if index < max_index {
25+
max_index = index;
26+
}
27+
}
28+
Ordering::Greater => {
29+
max_duration = duration;
30+
max_index = index;
31+
}
32+
}
33+
34+
prev_index = index;
35+
prev_time = time;
36+
});
37+
38+
max_index.cast_signed()
39+
}
40+
}
41+
42+
// ------------------------------------------------------ snip ------------------------------------------------------ //
43+
44+
impl super::Solution for Solution {
45+
fn button_with_longest_time(events: Vec<Vec<i32>>) -> i32 {
46+
Self::button_with_longest_time(events)
47+
}
48+
}
49+
50+
#[cfg(test)]
51+
mod tests {
52+
#[test]
53+
fn test_solution() {
54+
super::super::tests::run::<super::Solution>();
55+
}
56+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn button_with_longest_time(events: Vec<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, 2], [2, 5], [3, 9], [1, 15]] as &[_], 1),
14+
(&[[10, 5], [1, 7]], 10),
15+
];
16+
17+
for (events, expected) in test_cases {
18+
assert_eq!(
19+
S::button_with_longest_time(events.iter().map(Vec::from).collect()),
20+
expected,
21+
);
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)