Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 875 · Binary Search on Answer

Koko Eating Bananas

LeetCode 875 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Binary search on the answer (speed).

ಮಧ್ಯಮArrayBinary Search
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Koko Eating Bananas (LeetCode 875) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Binary Search on Answer ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

If Koko can finish at speed s, she can also finish at any faster speed — feasibility is monotonic. So binary search the smallest speed whose total hours (sum of ceil(pile / speed)) fits within h.

Approach

  1. 1

    Search speeds in [1, max(piles)].

  2. 2

    hours(speed) = Σ ceil(pile / speed).

  3. 3

    Feasible → try slower (high = mid − 1); else faster.

  4. 4

    low ends at the minimum feasible speed.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Binary search on speedPythonO(n log M) time · O(1) space
class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        #min of max pattern - BS
        #if she can eat within pile/speed hour and hour still remains, she will wait for the rest of the hour, so we need to take the higher value 
        #10 pile, speed is 3, she can finish 3.33 hours but she will wait till 4 hours
        def isFeasible(speed):
            hours_taken = 0
            for pile in piles:
                hours_taken+=ceil(pile/speed)
            return True if hours_taken<=h else False
        low = 1
        high = max(piles) 
        while low<=high:
            mid = (low+high)//2
            if isFeasible(mid):
                high = mid-1
            else:
                low = mid+1
        return low
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Koko Eating Bananas — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Koko Eating Bananas ಹಿಂದಿನ intuition ಏನು?

If Koko can finish at speed s, she can also finish at any faster speed — feasibility is monotonic. So binary search the smallest speed whose total hours (sum of ceil(pile / speed)) fits within h.

Koko Eating Bananas (LeetCode 875) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Search speeds in [1, max(piles)]. 2. hours(speed) = Σ ceil(pile / speed). 3. Feasible → try slower (high = mid − 1); else faster. 4. low ends at the minimum feasible speed.

Koko Eating Bananas ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log M). Space: O(1). (Accepted approach: Binary search on speed.)

Koko Eating Bananas ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Use ceil — a partly eaten pile still costs a whole hour.