-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1011. Capacity To Ship Packages Within D Days
52 lines (48 loc) · 1.36 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
51
52
class Solution
{
public static int findDays(int[] weights, int cap)
{
int days = 1; //First day.
int load = 0;
int n = weights.length; //size of array.
for (int i = 0; i < n; i++)
{
if (load + weights[i] > cap)
{
days += 1; //move to next day
load = weights[i]; //load the weight.
}
else
{
//load the weight on the same day.
load += weights[i];
}
}
return days;
}
public int shipWithinDays(int[] weights, int d)
{
int low = Integer.MIN_VALUE, high = 0;
for (int i = 0; i < weights.length; i++)
{
high += weights[i];
low = Math.max(low, weights[i]);
}
while (low <= high)
{
int mid = (low + high) / 2;
int numberOfDays = findDays(weights, mid);
if (numberOfDays <= d)
{
//eliminate right half
high = mid - 1;
}
else
{
//eliminate left half
low = mid + 1;
}
}
return low;
}
}