Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1011 · Binary Search on Answer

Capacity To Ship Packages Within D Days

LeetCode 1011 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Binary search capacity in [max(w), sum(w)] with a greedy day count.

मध्यमArrayBinary Search

मी Capacity To Ship Packages Within D Days (LeetCode 1011) असा सोडवला — Binary Search on Answer पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

A larger ship capacity never needs more days, so binary search the capacity. The smallest possible is the heaviest package; the largest is everything in one day. Check each guess by loading packages greedily in order.

Approach

  1. 1

    low = max(weights), high = sum(weights).

  2. 2

    Greedy: start a new day when the next package would overflow.

  3. 3

    days ≤ D → shrink high; else raise low.

मी कसा सोडवला

Binary search + greedy checkPythonO(n log S) time
class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        def is_feasibile(max_capacity):
            req_days = 1
            cur_taken= 0
            for weight in weights:
                if cur_taken+weight>max_capacity:
                    req_days+=1
                    cur_taken=weight
                else:
                    cur_taken+=weight
            return True if req_days<=days else False
        low=max(weights)
        high =sum(weights)
        while low<=high:
            mid = (low+high)//2
            if is_feasibile(mid):
                high = mid-1
            else:
                low = mid+1
        return low
स्टेप-थ्रू लोड होत आहे…

Capacity To Ship Packages Within D Days — वारंवार विचारले जाणारे प्रश्न

Capacity To Ship Packages Within D Days मागील intuition काय आहे?

A larger ship capacity never needs more days, so binary search the capacity. The smallest possible is the heaviest package; the largest is everything in one day. Check each guess by loading packages greedily in order.

Capacity To Ship Packages Within D Days (LeetCode 1011) कसा सोडवावा?

1. low = max(weights), high = sum(weights). 2. Greedy: start a new day when the next package would overflow. 3. days ≤ D → shrink high; else raise low.

Capacity To Ship Packages Within D Days ची time आणि space complexity किती आहे?

Time: O(n log S). Space: O(1). (Accepted approach: Binary search + greedy check.)

Capacity To Ship Packages Within D Days मध्ये सामान्य चुका कोणत्या?

Packages must stay in order — no sorting.