Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func shipWithinDays(_ weights: [Int], _ D: Int) -> Int {
- var start = Int.max
- var end = 0
- for w in weights{
- start = min(start, w)
- end += w
- }
- //guess the w
- while start + 1 < end{
- let mid = (start + end) / 2
- if !canShip(weights, D, mid) { //如果不能ship 说明给的weight太小
- start = mid
- }else{
- end = mid
- }
- }
- if canShip(weights, D, start) { return start}
- return end
- }
- func canShip(_ arr: [Int], _ D: Int, _ weight: Int) -> Bool{
- var curw = 0
- var count = 1
- for w in arr{
- if curw + w > weight{
- count += 1
- curw = w
- if count > D || curw > weight{
- return false
- }
- }else{
- curw += w
- }
- }
- return true
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement