Suppose there is a conveyor belt has packages that will be shipped from one port to another within D days. Here the i-th package on the conveyor belt has a weight of weights[i]. Each day, we will load the ship with packages on the belt. We will not load more weight than the maximum weight capacity of the ship. We have to find the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days. So if the input is like [3,2,2,4,1,4] and D = 3, then the output will be 6, as a ship capacity of 6 is the minimum to ship all the packages in 3 days, like −
Day 1: 3, 2
Day 2: 2, 4
Day 3: 1, 4
To solve this, we will follow these steps −
Define a recursive function solve(). This will take weights array, maxWeight, and ships array, this will act like −
index := 0
for i in range 0 to length of ships array
ships[i] := 0
while index < length of weights and ships[i] + weights[index] <= maxWeight
ships[i] := ships[i] + weights[index]
increase index by 1
return true, when index = length of weights, otherwise false
The main method will act like
ships := an array of size same as D, and fill it with 0
maxWeight := maximum of weights
low := maxWeight, high := maxWeight + length of weights array + 1
while low < high
mid := low + (high - low)/2
if solve(weights, mid, ships) is true, then high := mid, otherwise low := mid + 1
return high
Let us see the following implementation to get better understanding −
Example
class Solution(object): def shipWithinDays(self, weights, D): ships = [0 for i in range(D)] max_w = max(weights) low = max_w high = max_w * len(weights)+1 while low<high: mid = low + (high-low)//2 if self.solve(weights,mid,ships): high = mid else: low = mid+1 return high def solve(self,weights,max_w,ships): index = 0 for i in range(len(ships)): ships[i] = 0 while index < len(weights) and ships[i]+weights[index]<= max_w: ships[i] += weights[index] index+=1 return index == len(weights) ob = Solution() print(ob.shipWithinDays([3,2,2,4,1,4],3))
Input
[3,2,2,4,1,4] 3
Output
6