1011. Capacity To Ship Packages Within D Days
This page provides solutions for the leetcode problem 1011. Capacity To Ship Packages Within D Days.
Problem Explanation
The problem is asking us to calculate the least weight capacity of the ship that will allow all the packages on the conveyor belt to be shipped within a days.
Solution
This problem can be solved using the Binary Search technique. More such questions can be found here.
- Java
class Solution {
public int shipWithinDays(int[] weights, int days) {
int lo = Integer.MIN_VALUE;
int hi = 0;
for(int i = 0; i < weights.length; i++) {
lo = Math.max(lo, weights[i]);
hi += weights[i];
}
while(lo < hi) {
int mid = lo + (hi - lo) / 2;
boolean isMoreDays = daysRequired(weights, mid, days);
if(isMoreDays) lo = mid + 1;
else hi = mid;
}
return lo;
}
private boolean daysRequired(int[] weights, int capacity, int days) {
int required = 0, index = 0, sum = 0, requiredDays = 1;
while(index < weights.length) {
sum += weights[index];
if(sum > capacity) {
sum = weights[index];
requiredDays++;
}
index++;
if(requiredDays > days) return true;
}
return false;
}
}
Complexity
Let's say there are elements in an array, and total sum of all elements in an array is .
Time Complexity
The time complexity is for searching the optimal solution using binary search, and for checking if the array can be split into subarrays, so total time complexity will be:
Space Complexity
The solution uses constant space for storing binary search variables, so space complexity will be: