Skip to content

Commit

Permalink
Add problem 1986: Minimum Number of Work Sessions to Finish the Tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 4, 2024
1 parent c3f8628 commit 7b40766
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,7 @@ pub mod problem_1980_find_unique_binary_string;
pub mod problem_1981_minimize_the_difference_between_target_and_chosen_elements;
pub mod problem_1984_minimum_difference_between_highest_and_lowest_of_k_scores;
pub mod problem_1985_find_the_kth_largest_integer_in_the_array;
pub mod problem_1986_minimum_number_of_work_sessions_to_finish_the_tasks;
pub mod problem_1991_find_the_middle_index_in_array;
pub mod problem_1994_the_number_of_good_subsets;
pub mod problem_1996_the_number_of_weak_characters_in_the_game;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn min_sessions(tasks: Vec<i32>, session_time: i32) -> i32 {
let session_time = session_time as u8;
let total_combinations = 1 << tasks.len();
let mut cache = vec![(0_u8, 0_u8); total_combinations].into_boxed_slice();

cache[0].1 = session_time;

for combination in 1..total_combinations {
let mut bits = combination;
let mut best = (u8::MAX, u8::MAX);

loop {
let last_task = bits.trailing_zeros();
let last_bit = 1 << last_task;
let prev_session = cache[combination ^ last_bit];
let task_time = tasks[last_task as usize] as u8;
let candidate = prev_session.1 + task_time;

best = best.min(if candidate <= session_time {
(prev_session.0, candidate)
} else {
(prev_session.0 + 1, task_time)
});

bits ^= last_bit;

if bits == 0 {
break;
}
}

cache[combination] = best;
}

i32::from(cache.last().unwrap().0)
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn min_sessions(tasks: Vec<i32>, session_time: i32) -> i32 {
Self::min_sessions(tasks, session_time)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod dynamic_programming;

pub trait Solution {
fn min_sessions(tasks: Vec<i32>, session_time: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
((&[1, 2, 3] as &[_], 3), 2),
((&[3, 1, 3, 1, 1], 8), 2),
((&[1, 2, 3, 4, 5], 15), 1),
];

for ((tasks, session_time), expected) in test_cases {
assert_eq!(S::min_sessions(tasks.to_vec(), session_time), expected);
}
}
}

0 comments on commit 7b40766

Please sign in to comment.