../ Competitive Programming
-rw-r--r--aguang974 B1 min read

Leet Code Daily 2024-05-04 - Boats to Save People

Solution

  • First, sort all people in incresing order.
  • Let's say people[i..j] are the people which are not shipped yet.
  • There are several cases:
    • i == j, then we only need last boat.
    • people[i] + people[j] <= limit, then we carry both of them.
    • otherwise, people[j] must be shipped alone.

Code

c++
class Solution {
public:
    int numRescueBoats(vector<int>& people, int limit) {
        sort(people.begin(), people.end());
        int ans = 0;
        for (int i = 0, j = people.size() - 1; i <= j; ) {
            if (i == j) {
                ans++;
                i++;
            } else if (people[i] + people[j] <= limit) {
                i++;
                j--;
                ans++;
            } else {
                j--;
                ans++;
            }
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window