diff --git a/src/lib.rs b/src/lib.rs index 70f18e8f..17f8b016 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1437,6 +1437,7 @@ pub mod problem_2057_smallest_index_with_equal_value; pub mod problem_2058_find_the_minimum_and_maximum_number_of_nodes_between_critical_points; pub mod problem_2059_minimum_operations_to_convert_number; pub mod problem_2063_vowels_of_all_substrings; +pub mod problem_2064_minimized_maximum_of_products_distributed_to_any_store; pub mod problem_2068_check_whether_two_strings_are_almost_equivalent; pub mod problem_2069_walking_robot_simulation_ii; pub mod problem_2070_most_beautiful_item_for_each_query; diff --git a/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/binary_search.rs b/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/binary_search.rs new file mode 100644 index 00000000..65f40f8b --- /dev/null +++ b/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/binary_search.rs @@ -0,0 +1,56 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::num::NonZeroU32; + +impl Solution { + fn check(mut n: u32, quantities: &[i32], limit: NonZeroU32) -> bool { + for &quantity in quantities { + let required = (quantity as u32 + limit.get() - 1) / limit; + + if n < required { + return false; + } + + n -= required; + } + + true + } + + pub fn minimized_maximum(n: i32, quantities: Vec) -> i32 { + let n = n as u32; + let quantities = quantities.as_slice(); + let mut left = 1; + let mut right = quantities.iter().map(|&x| x as u32).max().unwrap(); + + while left < right { + let middle = (left + right) / 2; + + if Self::check(n, quantities, NonZeroU32::new(middle).unwrap()) { + right = middle; + } else { + left = middle + 1; + } + } + + left as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn minimized_maximum(n: i32, quantities: Vec) -> i32 { + Self::minimized_maximum(n, quantities) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/mod.rs b/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/mod.rs new file mode 100644 index 00000000..7e8c214e --- /dev/null +++ b/src/problem_2064_minimized_maximum_of_products_distributed_to_any_store/mod.rs @@ -0,0 +1,22 @@ +pub mod binary_search; + +pub trait Solution { + fn minimized_maximum(n: i32, quantities: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ((6, &[11, 6] as &[_]), 3), + ((7, &[15, 10, 10]), 5), + ((1, &[100_000]), 100_000), + ]; + + for ((n, quantities), expected) in test_cases { + assert_eq!(S::minimized_maximum(n, quantities.to_vec()), expected); + } + } +}