classSolution{ publicintshipWithinDays(int[] weights, int days){ int minWeight = Integer.MIN_VALUE; int maxWeight = 0; int len = weights.length; for (int i = 0; i < len; i++) { maxWeight += weights[i]; if (weights[i] > minWeight) { minWeight = weights[i]; } } int left = minWeight; int right = maxWeight; while (left <= right) { int mid = left + (right - left) / 2; int currentDays = calculateDays(weights, mid); if (currentDays == days) { right = mid - 1; } elseif (currentDays < days) { right = mid - 1; } elseif (currentDays > days) { left = mid + 1; } } return left; }
publicintcalculateDays(int[] weights, int weight){ int days = 0; int i = 0; int tmpWeight = weight; while (i < weights.length) { if (tmpWeight >= weights[i]) { tmpWeight -= weights[i]; i++; if (i == weights.length) { days++; } } else { tmpWeight = weight; days++; } } return days; } }