func shipWithinDays(_ weights: [Int], _ D: Int) -> Int {
var start = weights.max()!
var end = weights.reduce(0,+)
while start < end {
let mid = start + (end - start) / 2
let days = shipDays(weights, mid)
if days == D {
end = mid
} else if days < D {
end = mid
} else {
start = mid + 1
}
}
return start
}
private func shipDays(_ weights: [Int], _ limit: Int) -> Int {
var i = 0
var sum = 0
var days = 1
while i < weights.count {
if sum + weights[i] > limit {
sum = weights[i]
days += 1
} else {
sum += weights[i]
}
i += 1
}
return days
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme