Advertisement
HXXXXJ

1011. Capacity To Ship Packages Within D Days

Apr 13th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.99 KB | None | 0 0
  1. func shipWithinDays(_ weights: [Int], _ D: Int) -> Int {
  2.         var start = Int.max
  3.         var end = 0
  4.         for w in weights{
  5.             start = min(start, w)
  6.             end += w
  7.         }
  8.        
  9.         //guess the w
  10.         while start + 1 < end{
  11.             let mid = (start + end) / 2
  12.             if !canShip(weights, D, mid) {  //如果不能ship 说明给的weight太小
  13.                 start = mid
  14.             }else{
  15.                 end = mid
  16.             }
  17.         }
  18.         if canShip(weights, D, start) { return start}
  19.         return end
  20.     }
  21.    
  22.    
  23.     func canShip(_ arr: [Int], _ D: Int, _ weight: Int) -> Bool{
  24.         var curw = 0
  25.         var count = 1
  26.         for w in arr{
  27.             if curw + w > weight{
  28.                 count += 1
  29.                 curw = w
  30.                 if count > D || curw > weight{
  31.                     return false
  32.                 }
  33.             }else{
  34.                 curw += w
  35.             }
  36.         }
  37.         return true
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement