Skip to content

Commit 94843ce

Browse files
committed
ADDED
1 parent db0d111 commit 94843ce

File tree

2 files changed

+77
-25
lines changed

2 files changed

+77
-25
lines changed

.idea/workspace.xml

Lines changed: 30 additions & 25 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.thealgorithm.binsearch;
2+
3+
/**
4+
* @author: Subham Santra
5+
*/
6+
public class KokoEatingBananas {
7+
public int minEatingSpeed(int[] piles, int h) {
8+
long hi = 0L;
9+
long lo = 1;
10+
for (int pile : piles) {
11+
hi = Math.max(pile, hi);
12+
}
13+
// System.out.printf("Range speed %d to %d\n", lo, hi);
14+
// start binary search
15+
long minimumSpeed = 1L;
16+
while (lo <= hi) {
17+
long mid = ((hi - lo) >> 1) + lo;
18+
long kokoFinishTime = kokoFinishTime(piles, mid);
19+
// System.out.printf("finish time %d for speed %d\n", kokoFinishTime, mid);
20+
if (kokoFinishTime <= h) {
21+
// Taking exact same time or even less, we shall reduce speed and check
22+
minimumSpeed = mid;
23+
hi = mid - 1;
24+
} else {
25+
// Taking more time to finish, to reduce time, we need to increase speed
26+
lo = mid + 1;
27+
}
28+
}
29+
return (int) minimumSpeed;
30+
}
31+
32+
long kokoFinishTime(int[] piles, long speed) {
33+
long carry = 0L;
34+
for (double pile : piles) {
35+
carry += (long) Math.ceil(pile / speed);
36+
}
37+
return carry;
38+
}
39+
40+
public static void main(String[] args) {
41+
System.out.println(new KokoEatingBananas().minEatingSpeed(new int[] {3, 6, 7, 11}, 8));
42+
System.out.println(new KokoEatingBananas().minEatingSpeed(new int[] {100}, 99));
43+
System.out.println(
44+
new KokoEatingBananas()
45+
.minEatingSpeed(new int[] {805306368, 805306368, 805306368}, 1000000000));
46+
}
47+
}

0 commit comments

Comments
 (0)