-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-10-23-KokoEatingBananas.cpp
More file actions
45 lines (37 loc) · 1.07 KB
/
02-10-23-KokoEatingBananas.cpp
File metadata and controls
45 lines (37 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
Time: O( n log m ) m = maxBananas, n = piles.size()
Space: O(1)
https://leetcode.com/problems/koko-eating-bananas/
*/
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int minBananas = 1;
int maxBananas = -1;
for (int i = 0; i < piles.size(); i++) {
if (maxBananas < piles[i]) { //
maxBananas = piles[i];
}
}
while (minBananas <= maxBananas) {
int mid = minBananas + (maxBananas - minBananas) / 2;
long long hours = calcHours(piles, mid);
if (hours > h) {
minBananas = mid + 1;
} else {
maxBananas = mid - 1;
}
}
return minBananas;
}
long long calcHours(vector<int>& piles, int bananasPerHour) {
long long hours = 0;
for (int i = 0; i < piles.size(); i++) {
hours += piles[i] / bananasPerHour;
if (piles[i] % bananasPerHour != 0) {
hours++;
}
}
return hours;
}
};