oneby7

Binary Search Searching the answer

247. Capacity To Ship Packages Within D Days

Medium

Packages wait on a dock in a fixed order, and package i weighs weights[i]. A ship takes them away, one trip per day. Each day it loads the next packages in line, and their total weight must not be more than the ship's capacity. A package cannot be split, skipped or loaded ahead of the ones before it.

Return the smallest capacity that lets the ship carry every package within days days. Finishing in fewer days is fine.

Example 1

Input: weights = [4, 9, 2, 7, 3, 5, 8, 1], days = 4

Output: 13

Explanation: At capacity 13 the four days carry [4, 9], [2, 7, 3], [5, 8] and [1], with loads 13, 12, 13 and 1. At capacity 12 the ship needs five days.

Example 2

Input: weights = [2, 1, 10, 1, 2], days = 4

Output: 10

Explanation: The package of weight 10 has to fit on the ship, so the capacity is at least 10. At 10 the ship needs only three days, [2, 1], [10] and [1, 2], and that is within 4.

Example 3

Input: weights = [1000000000, 1000000000, 1000000000] days = 1

Output: 3000000000

Check your understanding

Work out the answer for this input before you write any code.

weights = [5, 1, 4, 2, 3], days = 2

Constraints

  • 1 ≤ weights.length ≤ 105
  • 1 ≤ weights[i] ≤ 109
  • 1 ≤ days ≤ weights.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.