File tree 1 file changed +51
-1
lines changed 1 file changed +51
-1
lines changed Original file line number Diff line number Diff line change 1
1
#![ allow( dead_code) ]
2
2
3
3
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
5
47
}
6
48
49
+ /*
50
+ Algorithm - Binary Search
51
+ -------------------------
52
+
53
+ Time Complexity: O(n log n)
54
+ Space Complexity: O(1)
55
+ */
56
+
7
57
#[ cfg( test) ]
8
58
mod tests {
9
59
use super :: * ;
You can’t perform that action at this time.
0 commit comments