-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_1011.java
More file actions
42 lines (39 loc) · 1.21 KB
/
_1011.java
File metadata and controls
42 lines (39 loc) · 1.21 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
package com.github.aditya;
public class _1011 {
class Solution {
// 8 ms, faster than 91.36%, Memory 42.1 MB, less than 56.78%
public int shipWithinDays(int[] weights, int days) {
int left = 0, right = 0;
for (int i = 0; i < weights.length; i++) {
if (weights[i] > left)
left = weights[i];
right = right + weights[i];
}
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (isValid(weights, days, mid)) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
private boolean isValid(int[] arr, int days, int mid) {
int count = 1;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
if (sum > mid) {
count++;
sum = arr[i];
}
if (count > days)
return false;
}
return true;
}
}
}