classSolution{publicintshipWithinDays(int[] weights,int days){int sum =0;// Sum of the weights of the cargosfor(int cargo : weights){
sum += cargo;}int min =1, max = sum;// At least 1 capacity per day, max is the total sum which can ship the cargos at onceint res =0;// Final result// Binary search for the min capacity within "days" timeframewhile(min <= max){int mid = min +(max - min)/2;// Current capacityint weightSum =0;// Total sum of current weightsboolean canLiftOneMinCargo =true;// Flag to indicate the current capacity is not possible to lift the min. weight cargoint k =1;// Days required with current capacity// Check required days if ship with the current capacityfor(int i =0; i < weights.length;++i){// Capacity is not possible to ship even 1 cargoif(mid < weights[i]){
canLiftOneMinCargo =false;break;// This capacity is impossible}
weightSum += weights[i];// Exceed one shipment capacityif(weightSum > mid){// Start another day
weightSum =0;++k;// Day + 1--i;// Ship current cargo in tomorrow}}// This capacity is validif(canLiftOneMinCargo && k <= days){
res = mid;// Assign current capacity
max = mid -1;// See if we can do it in less capacity}else{// Invalid, should increase the capacity
min = mid +1;}}return res;}}