> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/binary-search/875.-koko-eating-bananas.md).

# 875. Koko Eating Bananas

```
Binary search
```

```
T:O(n + plogp) - p is piles value, n is piles length
S:O(1)
```

````java
```java
class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1;
        int right = 0;
        for (int pile : piles) {
            right = Math.max(right, pile);
        }
        while (left < right) {
            int mid = left + (right - left)/2;
            int count = 0;
            for (int pile : piles) {
                if (mid == 0) {
                    return left;
                } else {
                    count += pile/mid + (pile%mid != 0 ? 1 : 0);
                }
            }
            if (count <= h) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}

/*
Binary search
T:O(n + plogp) - p is piles value, n is piles length
S:O(1)


piles = [3,6,7,11], h = 8

h = 8

3, 6, 7, 11
1 2.  2. 3

32

piles[i]/k + (piles[i]%k != 0 ? 1 : 0)


*/
```
````

### new version

<pre class="language-java"><code class="lang-java">```java
class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int right = 0;
        int left = 1;
        int test = 0;
        for (int pile : piles) {
            right = Math.max(right, pile);
            test += pile;
        }
        while (left &#x3C;= right) {
            int mid = left + (right - left)/2;
            long hours = getHour(piles, mid);
            
            if (hours &#x3C; h) {
                right = mid - 1;
            } else if (hours > h){
                left = mid + 1;
            } else {
                if (mid-1 >= 0 &#x26;&#x26; getHour(piles, mid-1) == h) {
                    right = mid - 1; 
                } else {
                    return mid;
                }
            }
        }
        return left;
    }
    // for new test case: piles = [805306368,805306368,805306368]
<strong>    // h = 1000000000
</strong><strong>    // getHour with int will become negative, so use long to add
</strong>    long getHour(int[] piles, int mid) {
        long hours = 0;
        for (int pile : piles) {
            hours += ((long)pile/mid + (pile%mid != 0 ? 1 : 0));
        }
        return hours;
    }
}

/*
h = 8
3 6 7 11
6
1.1 2. 2 &#x3C; 8

hour and k is relatively

3~11

3+11)/2 = 7

3 7 -> 5
3 5
8/2 = 4

3 4
7/2 = 3

3 6 7 11
1 2 2 3

1 2 3 4 -> over h = 8
*/
```
</code></pre>
