Boats to Save People

You are given an array people where people[i] is the weight of the ith person, and an unlimited number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of their weights is at most limit. Return the minimum number of boats to carry every given person.

30:00

Boats to Save People
medium
Free written solution
Topics
Companies

You are given an array people where people[i] is the weight of the ith person, and an unlimited number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of their weights is at most limit. Return the minimum number of boats to carry every given person.

Example 1:
Input: {"people":[1,2],"limit":3}
Output: 1
Constraints:
  • 1≤people.length≤5×1041 \leq \text{people.length} \leq 5 \times 10^4

  • 1≤people[i]≤limit≤3×1041 \leq \text{people}[i] \leq \text{limit} \leq 3 \times 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"people":[1,2],"limit":3}

2 people wait on the dock. Each boat holds at most two people and at most 3 in weight.

Dock (unsorted)

1

2

dashed line = limit 3

Boats launched

boats = 0

no boats yet

L lightest left

H heaviest left

boat capacity 3

Variables
VariableValue
limit3
light0
heavy1
boats0
DepthFunction Call
Stack empty
0/4