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.