Skip to content

Commit e167b07

Browse files
authored
Merge pull request neetcode-gh#1035 from ritesh-dt/main
Add solution for 875 - Koko Eating Bananas in C
2 parents f3a9c52 + 1cd777a commit e167b07

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

c/875-Koko-Eating-Bananas.c

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
Given a array of bananas piles containing differing amounts of bananas and
3+
'h' hours to eat all of them.
4+
Determine the minimum speed (i.e. numberbananas per-hour) possible.
5+
6+
Ex. piles = [3,6,7,11], h = 8 -> 4
7+
8+
If all the bananas can be eaten with speed 'x' than the same holds true for
9+
any speed more than 'x'. Similarly if bananas cannot be eated at speed 'y',
10+
the same will be speeds less than 'y'.
11+
12+
Binary search can be performed on the possible values of speed till the
13+
minimum speed is found with,
14+
left bound = ceil(total/h)
15+
right bound = maximum pile size
16+
17+
Time: O(NlogM) where N is number of piles and M is maximum pile size
18+
Space: O(1)
19+
*/
20+
21+
int hoursRequired(int* piles, int pilesSize, int h, int speed) {
22+
int hours = 0;
23+
for (int i = 0; i < pilesSize; ++i) {
24+
hours += (piles[i]+speed-1)/speed;
25+
}
26+
27+
return hours;
28+
}
29+
30+
long sumOfArray(int* piles, int pilesSize) {
31+
long total = 0l;
32+
33+
for (int i = 0; i < pilesSize; ++i) {
34+
total += piles[i];
35+
}
36+
37+
return total;
38+
}
39+
40+
int maxElement(int* piles, int pilesSize) {
41+
int maxElem = piles[0];
42+
43+
for (int i = 0; i < pilesSize; ++i) {
44+
maxElem = fmax(maxElem, piles[i]);
45+
}
46+
return maxElem;
47+
}
48+
49+
int minEatingSpeed(int* piles, int pilesSize, int h){
50+
long total = sumOfArray(piles, pilesSize);
51+
52+
int l = (total+h-1)/h;
53+
int r = maxElement(piles, pilesSize);
54+
55+
while (l < r) {
56+
int mid = l + (r-l)/2;
57+
58+
int hours = hoursRequired(piles, pilesSize, h, mid);
59+
if (hours <= h)
60+
r = mid;
61+
else if (hours > h)
62+
l = mid + 1;
63+
}
64+
65+
return r;
66+
}

0 commit comments

Comments
 (0)