-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1011.capacity to ship packages within d days
50 lines (50 loc) · 1.16 KB
/
1011.capacity to ship packages within d days
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public int shipWithinDays(int[] weights, int days) {
int max=0;
// Arrays.sort(weights);
for(int i=0;i<weights.length;i++){
max+=weights[i];
}
int ans=binary(weights,days,1,max);
return ans;
}
static int binary(int arr[],int days,int s,int h){
int l=s;
int r=h;
int si=-1;
while(l<=r){
int mid=l+(r-l)/2;
if(all(mid,arr,days)){
// System.out.println("mid"+mid);
si=mid;
r=mid-1;
}
else{
l=mid+1;
}
}
return si;
}
static boolean all(int mid,int arr[],int d){
int sum=0;
int c=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
if(arr[i]>mid){
return false;
}
else if(sum==mid){
c+=1;
sum=0;
}
else if(sum>mid){
c+=1;
sum=arr[i];
}
}
if(sum!=0){
c=c+1;
}
return c<=d;
}
}