diff --git a/posts/two-pointers.html b/posts/two-pointers.html index 86192ba..64e39e7 100644 --- a/posts/two-pointers.html +++ b/posts/two-pointers.html @@ -84,13 +84,59 @@ r -= 1 return area - - - - - - - +

+ boats to save people +

+

+ Usually, the metaphorical problem description is a distraction. + However, I find that thinking within the confines of "boats" and + "people" yields an intuitive solution in this case. +

+

+ + Since only two people can fit in a boat at a time, pairing up + lightest and heaviest individuals will result in the least amount of + boats being used. +

+

+ However, the weights are given in random order. Efficiently pairing + up the lightest and heaviest individuals, then, requires the most + common two-pointers prepreocessing step: sorting. +

+

Finally, flesh out any remaining aspects of the implementation:

+
    +
  1. If one person remains, give them a boat.
  2. +
  3. + If both people don't fit, use the heavier person—the + lighter could maybe fit with someone else. +
  4. +
+
+
def minimum_rescue_boats(people: list[int], limit: int) -> int:
+    boats = 0
+    light = 0
+    heavy = len(people) - 1
+
+    people.sort()
+
+    while light <= heavy:
+        if light == heavy:
+            boats += 1
+            break
+        elif people[light] + people[heavy] <= limit:
+            boats += 1
+            light += 1
+            heavy -= 1
+        else:
+            boats += 1
+            heavy -= 1
+
+    return boats
+