1. Brute Force — Quadratic Greedy Pairing with Used Array
Intuition
Sort people. Mark all people as unused. From right to left, find the next unplaced person. Then scan all unused lighter people to find the heaviest one who can share the boat. Mark them used and increment boat count.
When to apply: When N <= 200.
Algorithm
- Step 1: Sort people ascending.
- Step 2: Initialize boolean array used of size N to false.
- Step 3: For i from N - 1 down to 0: if used[i], continue.
- Step 4: Find largest j < i such that !used[j] and people[i] + people[j] <= limit.
- Step 5: If found, used[j] = true. Mark used[i] = true, increment boats.
- Step 6: Return boats.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int numRescueBoats(vector<int>& people, int limit) { sort(people.begin(), people.end()); int n = people.size(); vector<bool> used(n, false); int boats = 0; for (int i = n - 1; i >= 0; --i) { if (used[i]) continue; used[i] = true; for (int j = i - 1; j >= 0; --j) { if (!used[j] && people[i] + people[j] <= limit) { used[j] = true; break; } } boats++; } return boats; }}; int main() { Solution sol; vector<int> people = {3, 2, 2, 1}; int limit = 3; cout << "Min boats: " << sol.numRescueBoats(people, limit) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Outer loop runs N times, inner loop scans up to N times. - Space complexity:
O(N)— Boolean used array of size N.
Why Brute Force Doesn't Scale:
With N = 50,000, N2 is 2.5 * 109 operations, which times out. Two pointers on sorted array runs in ~15ms.
For N = 50,000: O(N log N) requires ~8 * 105 operations, executing in under 20ms.