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.