Skip to content

Commit 0358ee0

Browse files
committed
Add problem 875: Koko Eating Bananas
1 parent 1fc99b4 commit 0358ee0

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,7 @@ pub mod problem_0869_reordered_power_of_2;
717717
pub mod problem_0870_advantage_shuffle;
718718
pub mod problem_0872_leaf_similar_trees;
719719
pub mod problem_0874_walking_robot_simulation;
720+
pub mod problem_0875_koko_eating_bananas;
720721
pub mod problem_1143_longest_common_subsequence;
721722
pub mod problem_1192_critical_connections_in_a_network;
722723
pub mod problem_1342_number_of_steps_to_reduce_a_number_to_zero;
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
fn div_ceil(lhs: u32, rhs: u32) -> u32 {
7+
let result = lhs / rhs;
8+
9+
if lhs % rhs == 0 {
10+
result
11+
} else {
12+
result + 1
13+
}
14+
}
15+
16+
fn check(piles: &[i32], h: u32, speed: u32) -> bool {
17+
piles.iter().map(|&pile| Self::div_ceil(pile as _, speed)).sum::<u32>() > h
18+
}
19+
20+
pub fn min_eating_speed(piles: Vec<i32>, h: i32) -> i32 {
21+
let h = h as u32;
22+
let mut total = 0;
23+
let mut max = 0;
24+
25+
for &pile in &piles {
26+
let pile = pile as u32;
27+
28+
total += pile;
29+
max = max.max(pile);
30+
}
31+
32+
let mut low = Self::div_ceil(total, h);
33+
let mut high = max;
34+
35+
while low < high {
36+
let middle = (low + high) / 2;
37+
38+
if Self::check(&piles, h, middle) {
39+
low = middle + 1;
40+
} else {
41+
high = middle;
42+
}
43+
}
44+
45+
low as _
46+
}
47+
}
48+
49+
// ------------------------------------------------------ snip ------------------------------------------------------ //
50+
51+
impl super::Solution for Solution {
52+
fn min_eating_speed(piles: Vec<i32>, h: i32) -> i32 {
53+
Self::min_eating_speed(piles, h)
54+
}
55+
}
56+
57+
#[cfg(test)]
58+
mod tests {
59+
#[test]
60+
fn test_solution() {
61+
super::super::tests::run::<super::Solution>();
62+
}
63+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod binary_search;
2+
3+
pub trait Solution {
4+
fn min_eating_speed(piles: Vec<i32>, h: 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+
((&[3, 6, 7, 11] as &[_], 8), 4),
14+
((&[30, 11, 23, 4, 20], 5), 30),
15+
((&[30, 11, 23, 4, 20], 6), 23),
16+
];
17+
18+
for ((piles, h), expected) in test_cases {
19+
assert_eq!(S::min_eating_speed(piles.to_vec(), h), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)