-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsolution1.js
More file actions
41 lines (39 loc) · 774 Bytes
/
solution1.js
File metadata and controls
41 lines (39 loc) · 774 Bytes
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
/**
* https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
*
* 1011. Capacity To Ship Packages Within D Days
*
* Medium
*
* 64ms 100%
* 27.8mb 42.60
*/
const shipWithinDays = (weights, D) => {
const len = weights.length
let min = Number.MIN_SAFE_INTEGER
let max = 0
for (let weight of weights) {
max += weight
min = Math.max(min, weight)
}
let ans = max
while (min < max) {
const mid = Math.floor((min + max) / 2)
let days = 1
let temp = 0
for (let i = 0; i < len; i++) {
temp += weights[i]
if (temp > mid) {
temp = weights[i]
days++
}
}
if (days <= D) {
max = mid
ans = ans < mid ? ans : mid
} else {
min = mid + 1
}
}
return ans
}