Leetcode 875: Koko Eating Bananas

89 Views Asked by At

Leetcode 875: Koko Eating Bananas

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1:

Input: piles = [3,6,7,11], h = 8
Output: 4

Example 2:

Input: piles = [30,11,23,4,20], h = 5
Output: 30

Example 3:

Input: piles = [30,11,23,4,20], h = 6
Output: 23

import java.util.Arrays;

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        Arrays.sort(piles);

        int j = 0;
        int high = piles[piles.length-1];
      int i = 0;
      int k;
      outerLoop1:
        for( k = piles[0]; k <= high; k++) {
            while (j <= h && i < piles.length) {
                if (piles[i] > 0) {
                    piles[i] = piles[i] - k;
                }
                j++;
                i++;
                if (i == piles.length) {
                    i = 0;
                }
            }
            outerLoop:
            if (j == h) {
                int f = 0;
                while (f < piles.length) {
                    if (piles[i] > 0) {
                        break outerLoop;
                    } else {
                        f++;
                    }
                    
                }
                break outerLoop1;
            }
        }
        return k;
    }
}

I know that I was supposed to solve this using binary search but I did a different approach.

I run a for loop starting from the lowest value of k, i.e. of the lowest val in piles and go upto the highest, returning k at just the moment when everything in the pile is 0 or 1 (after repeated subtraction of k from it). If that isn't the case, I increment k and try again. From what I understand, break outerLoop gets out of the if statement and k is incremented. Whereas break outerLoop1 gets out of the very outer for loop of k and k is returned cause I found the value of k I needed.

What's wrong in my logic here?

I don't need a solution for this problem but just clarification on what exactly is wrong with my specific version of code and what tweaks I can make to fix it, approaching it the way I am right now.

1

There are 1 best solutions below

0
Senozoid On

I run a for loop starting from the lowest value of k, i.e. of the lowest val in piles

Why is the minimum possible of k the lowest value in piles? Take the example: piles={8};h=8. Here, the minimum is 1, but your algorithm will never check that case because it starts checking at 8.