Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5315443

Browse files
committedSep 27, 2023
feat: add problem and algorithm description for koko eating bananas
1 parent 0552eab commit 5315443

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed
 

‎src/medium/koko_eating_bananas.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,59 @@
11
#![allow(dead_code)]
22

33
pub fn min_eating_speed(piles: Vec<i32>, h: i32) -> i32 {
4-
todo!("Solve this problem")
4+
// Find the maximum number of bananas in a pile.
5+
let max = piles.iter().max().unwrap(); // O(n)
6+
7+
// Binary search for the minimum eating speed.
8+
// The minimum eating speed is 1.
9+
let mut left = 1;
10+
11+
// The maximum eating speed is the maximum number of bananas in a pile.
12+
let mut right = *max;
13+
14+
while left < right {
15+
// The middle eating speed.
16+
let mid = left + (right - left) / 2;
17+
18+
// The number of hours it takes to eat all bananas at the middle eating speed.
19+
let mut hours = 0;
20+
21+
for pile in &piles {
22+
// If the number of bananas in the pile is divisible by the middle eating speed,
23+
// then the number of hours it takes to eat all bananas in the pile is the number
24+
// of bananas in the pile divided by the middle eating speed.
25+
if pile % mid == 0 {
26+
hours += pile / mid;
27+
} else {
28+
// Otherwise, the number of hours it takes to eat all bananas in the pile is
29+
// the number of bananas in the pile divided by the middle eating speed plus
30+
// one.
31+
hours += pile / mid + 1;
32+
}
33+
}
34+
35+
// If the number of hours it takes to eat all bananas at the middle eating speed is
36+
// greater than the number of hours we have, then we need to increase the eating
37+
// speed.
38+
if hours > h {
39+
left = mid + 1;
40+
} else {
41+
// Otherwise, we need to decrease the eating speed.
42+
right = mid;
43+
}
44+
}
45+
46+
left
547
}
648

49+
/*
50+
Algorithm - Binary Search
51+
-------------------------
52+
53+
Time Complexity: O(n log n)
54+
Space Complexity: O(1)
55+
*/
56+
757
#[cfg(test)]
858
mod tests {
959
use super::*;

0 commit comments

Comments
 (0)
Please sign in to comment.