[Leetcode] 875. Koko Eating Bananas

whitehousechef·2025년 8월 11일

https://leetcode.com/problems/koko-eating-bananas/description/

initial

typical BS q but
1) careful of the mid value. If left and right is 0,0 or if left is 0 and right is 1, mid value is 0. We cannot divide something by 0. So left should be 1.

2) right should not be the sum of the nums list cuz if nums list has values that are close to infinity, it can overflow

3) tmp should be long or double, incase of overflow

sol

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int left=1,right=Arrays.stream(piles).max().getAsInt();
        while(left<right){
            int mid = left+(right-left)/2;
            double tmp=0;
            for(int i:piles){
                int q = i/mid, rem=i%mid;
                tmp+= (q+ ((rem>0) ?1:0));
            }
            if(tmp>h) left=mid+1;
            else right=mid;
        }
        return left;
    }
}

complexity

n time cuz even tho bs is log n the right value of streaming is n? no cuz we iter with for loop thats n and we do bs on that so it is n log n
1 space yes

0개의 댓글