-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathCapacityToShipPackagesWithInDDays.java
More file actions
44 lines (43 loc) · 1.06 KB
/
CapacityToShipPackagesWithInDDays.java
File metadata and controls
44 lines (43 loc) · 1.06 KB
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
class Solution {
public boolean isValid(int cap,int weights[],int days,int n)
{
int numDays=0;
int sumOfWeights=0;
for(int i=0;i<n;i++)
{
if(weights[i]>cap) return false;
sumOfWeights+=weights[i];
if(sumOfWeights>cap)
{
numDays++;
sumOfWeights=weights[i];
}
}
numDays++;
return numDays<=days;
}
public int shipWithinDays(int[] weights, int days) {
int minCap=Integer.MIN_VALUE;
int maxCap=0;
for(int i=0;i<weights.length;i++)
{
minCap=Math.max(minCap,weights[i]);
maxCap+=weights[i];
}
int capacity=0;
while(minCap<=maxCap)
{
int mid=(minCap+maxCap)/2;
if(isValid(mid,weights,days,weights.length))
{
capacity=mid;
maxCap=mid-1;
}
else
{
minCap=mid+1;
}
}
return capacity;
}
}