Boats to Save People

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array people where people[i] is the weight of the ith person, and an infinite number of boats each with a maximum weight limit, return the minimum number of boats to carry every person.

Each boat carries at most two people at the same time, provided the sum of their weights does not exceed limit.

Examples

Example 1:

Input: people = [1, 2], limit = 3

Output: 1

Explanation: 1 boat can carry both people (1 + 2 = 3 which equals the limit).

Example 2:

Input: people = [3, 2, 2, 1], limit = 3

Output: 3

Explanation: 3 boats are needed: (1, 2), (2), and (3).

Example 3:

Input: people = [3, 5, 3, 4], limit = 5

Output: 4

Explanation: No two people can share a boat since every pairing exceeds the limit. 4 boats are needed.

Constraints

  • 1 <= people.length <= 5 * 10⁴
  • 1 <= people[i] <= limit <= 3 * 10⁴
  • Each person can fit in a boat by themselves (i.e., people[i] <= limit)
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle