Capacity To Ship Packages Within D Days
LeetCode 1011 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Binary search capacity in [max(w), sum(w)] with a greedy day count.
నేను 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
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.
నేను ఎలా పరిష్కరించాను
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 lowCapacity 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.