Boats to Save People

You are given an array people where people[i] is the weight of the ith person and an integer limit representing the maximum weight a boat can carry. Each boat can carry at most two people at the same time, as long as the total weight does not exceed the limit. Return the minimum number of boats needed. Pattern focus: Sorting First. Sort the weights and pair the lightest remaining person with the heaviest remaining person whenever possible.

Input Format

people = weights of people, limit = boat weight limit

Output Format

minimum number of boats

Constraints

  • 1 <= people.length <= 5 * 10^4
  • 1 <= people[i] <= limit <= 10^9

Examples

Example 1:

Input:

people = [1,2]
limit = 3

Output:

1

Explanation:

Both people can share a single boat because their total weight is exactly 3.

Example 2:

Input:

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

Output:

3

Explanation:

Pair 1 with 2, and the remaining 2 and 3 each need their own boat.

Example 3:

Input:

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

Output:

4

Explanation:

Every person is too heavy to pair with any other person under the limit.

Loading...
Boats to Save People - Greedy DSA Problem