83 lines
3.0 KiB
Rust
83 lines
3.0 KiB
Rust
|
use std::cmp::max;
|
||
|
|
||
|
struct Solution;
|
||
|
impl Solution {
|
||
|
pub fn max_free_time(event_time: i32, start_time: Vec<i32>, end_time: Vec<i32>) -> i32 {
|
||
|
let mut first_selection = 0;
|
||
|
let mut second_selection = 0;
|
||
|
let mut third_selection = 0;
|
||
|
|
||
|
if end_time[end_time.len() - 1] < event_time {
|
||
|
first_selection = event_time - end_time[end_time.len() - 1];
|
||
|
}
|
||
|
let mut last_time = 0;
|
||
|
for i in 0..start_time.len() {
|
||
|
if start_time[i] > last_time {
|
||
|
let val = start_time[i] - last_time;
|
||
|
if val > first_selection {
|
||
|
third_selection = second_selection;
|
||
|
second_selection = first_selection;
|
||
|
first_selection = val;
|
||
|
} else if val > second_selection {
|
||
|
third_selection = second_selection;
|
||
|
second_selection = val;
|
||
|
} else if val > third_selection {
|
||
|
third_selection = val;
|
||
|
}
|
||
|
}
|
||
|
last_time = end_time[i];
|
||
|
}
|
||
|
|
||
|
let check_can_add = |left_space: i32, right_space: i32, needed: i32| -> bool {
|
||
|
if needed <= third_selection {
|
||
|
return true;
|
||
|
}
|
||
|
if needed <= second_selection {
|
||
|
if left_space == second_selection && right_space == first_selection ||
|
||
|
left_space == first_selection && right_space == second_selection {
|
||
|
return false;
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
if needed <= first_selection {
|
||
|
if left_space != first_selection && right_space != first_selection {
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
};
|
||
|
last_time = end_time[0];
|
||
|
let mut last = start_time[0];
|
||
|
let mut ans = start_time[0];
|
||
|
for i in 1..start_time.len() {
|
||
|
let left_space = last;
|
||
|
let right_space = start_time[i] - last_time;
|
||
|
let new_val = if check_can_add(left_space, right_space, end_time[i - 1] - start_time[i - 1]) {
|
||
|
left_space + right_space + end_time[i - 1] - start_time[i - 1]
|
||
|
} else {
|
||
|
left_space + right_space
|
||
|
};
|
||
|
ans = max(ans, new_val);
|
||
|
last = right_space;
|
||
|
last_time = end_time[i];
|
||
|
}
|
||
|
{
|
||
|
let left_space = last;
|
||
|
let right_space = event_time - last_time;
|
||
|
let new_val = if check_can_add(left_space, right_space, end_time[end_time.len() - 1] - start_time[end_time.len() - 1]) {
|
||
|
left_space + right_space + end_time[end_time.len() - 1]
|
||
|
- start_time[end_time.len() - 1]
|
||
|
} else {
|
||
|
left_space + right_space
|
||
|
};
|
||
|
ans = max(ans, new_val);
|
||
|
}
|
||
|
ans
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn main() {
|
||
|
let sl = Solution::max_free_time(5, vec![1, 3], vec![2, 5]);
|
||
|
println!("{}", sl);
|
||
|
}
|