Ctrl K

Rafts for Two

Medium
A group of hikers has to cross a river. The i-th hiker weighs weights[i]. There are as many rafts as you like, but each raft carries at most two people, and their combined weight must not exceed capacity. Return the smallest number of rafts needed to get everyone across.
Example 1
weights=[70, 50, 80, 40], capacity=120 → 2

80 and 40 fit together (120), and so do 70 and 50 (120): two rafts are enough.

Example 2
weights=[60, 90, 30, 100], capacity=100 → 3

100 and 90 each need a raft of their own. 60 and 30 weigh 90 together and share one. Three rafts in total.

Example 3
weights=[5, 5, 5], capacity=10 → 2

A raft holds at most two people, so the third one needs a raft of their own.

Constraints
  • 1 ≤ len(weights) ≤ 5·10⁴
  • 1 ≤ weights[i] ≤ capacity ≤ 3·10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStudios for Recording Sessions MediumFix the Middle of the Line MediumStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker MediumLining Up Against Rivals Medium
loading Python…
Input
weights=[70, 50, 80, 40], capacity=120
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.