0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #1011: Capacity To Ship Packages Within D Days

0
Posted at
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
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?