For the solution of this problem, we should be able to tell that it need a binary search.
The left value is the maxmum weight in the weight list, because if less than that, the package cannot be shipped.
The right value is the sum of the weight.
The solution's time complexity is log(n), n is the sum of the weight.
public int shipWithinDays(int[] weights, int days) { int l=0, r = 0; for (int i = 0; i < weights.length; i++) { l = Math.max(l, weights[i]); //The left is the max value of weights r += weights[i]; } int mid = 0, daynum = 0; while (l <= r) { mid = (l + r) / 2; daynum = helper(weights, mid); if (daynum <= days) {//even if the daynum == days, there might be smaller value meed the requirement r = mid-1; } else { l = mid + 1; } } return l; } private int helper(int[] weights, int mid) { int sum = 0; int i = 0; int days = 1; while (i < weights.length) { sum += weights[i]; if (sum <= mid) i++; else { days++; sum = 0; } } return days; }