1+ """
2+ LeetCode 1011. Capacity To Ship Packages Within D Days
3+
4+ Problem:
5+ Given an array of package weights and an integer days,
6+ return the least weight capacity of the ship that will
7+ result in all the packages being shipped within the given days.
8+
9+ Approach:
10+ Binary Search on Answer
11+
12+ Search Space:
13+ - Minimum capacity = max(weights)
14+ (because the ship must be able to carry the heaviest package)
15+
16+ - Maximum capacity = sum(weights)
17+ (because the ship can carry all packages in one day)
18+
19+ For each candidate capacity (mid):
20+ - Calculate how many days are required to ship all packages.
21+ - If required days <= given days:
22+ Capacity works, try a smaller capacity.
23+ - Otherwise:
24+ Capacity is too small, try a larger capacity.
25+
26+ Time Complexity:
27+ O(n * log(sum(weights)))
28+
29+ Space Complexity:
30+ O(1)
31+ """
32+
33+
34+ class Solution :
35+ def shipWithinDays (self , weights , days ):
36+ # Minimum possible capacity
37+ left = max (weights )
38+
39+ # Maximum possible capacity
40+ right = sum (weights )
41+
42+ while left <= right :
43+ mid = left + (right - left ) // 2
44+
45+ required_days = self .findDays (weights , mid )
46+
47+ # Capacity is sufficient
48+ if required_days <= days :
49+ right = mid - 1
50+
51+ # Capacity is too small
52+ else :
53+ left = mid + 1
54+
55+ # First valid minimum capacity
56+ return left
57+
58+ def findDays (self , weights , capacity ):
59+ days = 1
60+ current_load = 0
61+
62+ for weight in weights :
63+
64+ # Package doesn't fit in current day
65+ if current_load + weight > capacity :
66+ days += 1
67+ current_load = weight
68+
69+ # Package fits in current day
70+ else :
71+ current_load += weight
72+
73+ return days
74+
75+
76+ # Example Usage
77+ if __name__ == "__main__" :
78+ weights = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
79+ days = 5
80+
81+ solution = Solution ()
82+ answer = solution .shipWithinDays (weights , days )
83+
84+ print ("Minimum Ship Capacity:" , answer )
85+
86+ """
87+ Output:
88+ Minimum Ship Capacity: 15
89+ """
0 commit comments