Skip to content

Commit

Permalink
Add problem 2064: Minimized Maximum of Products Distributed to Any Store
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 9, 2024
1 parent 350f00e commit 6f5590a
Show file tree
Hide file tree
Showing 3 changed files with 79 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 @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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>) -> 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>) -> i32 {
Self::minimized_maximum(n, quantities)
}
}

#[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 binary_search;

pub trait Solution {
fn minimized_maximum(n: i32, quantities: Vec<i32>) -> i32;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 6f5590a

Please sign in to comment.