Boats to Save People - Problem

You are given an array people where people[i] is the weight of the i-th person, and an infinite 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 the weight of those people is at most limit.

Return the minimum number of boats to carry every given person.

Input & Output

Example 1 — Basic Pairing
$ Input: people = [1,2], limit = 3
Output: 1
💡 Note: Both people can fit in one boat: 1 + 2 = 3 ≤ 3, so we need only 1 boat total
Example 2 — Mixed Pairing
$ Input: people = [3,2,2,1], limit = 3
Output: 3
💡 Note: After sorting [1,2,2,3]: pair (1,2)→boat 1, remaining 2 and 3 need separate boats since 2+3>3
Example 3 — No Pairing Possible
$ Input: people = [5,5,5,5], limit = 5
Output: 4
💡 Note: Each person weighs exactly the limit, so each needs their own boat. Total: 4 boats

Constraints

  • 1 ≤ people.length ≤ 5 × 104
  • 1 ≤ people[i] ≤ limit ≤ 3 × 104

Visualization

Tap to expand
Boats to Save People INPUT people array: 1 index 0 2 index 1 Weight: 1 Weight: 2 Boat Capacity (limit) 3 people=[1,2], limit=3 ALGORITHM STEPS 1 Sort Array [1,2] (already sorted) 2 Two Pointers left=0, right=1 1 L 2 R 3 Check Sum 1 + 2 = 3 <= 3 4 Pair Together Both fit! boats++ 1 boat used FINAL RESULT 1 2 Output: 1 Minimum boats needed OK - All saved! 1+2=3, fits in 1 boat Key Insight: Sort the array first. Use two pointers: pair the lightest person (left) with the heaviest (right). If they fit together, move both pointers. Otherwise, send the heavy person alone. This greedy approach maximizes pairings and minimizes boats. Time: O(n log n) for sorting, Space: O(1). TutorialsPoint - Boats to Save People | Greedy with Sorting Approach
Asked in
Amazon 45 Google 32 Facebook 28 Microsoft 24
186.8K Views
Medium Frequency
~15 min Avg. Time
3.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen