feat(two-pointers): boats to save people
This commit is contained in:
parent
683fa2d802
commit
5549a1912f
1 changed files with 53 additions and 7 deletions
|
|
@ -84,13 +84,59 @@
|
|||
r -= 1
|
||||
return area</code></pre>
|
||||
</div>
|
||||
<!-- <h3> -->
|
||||
<!-- <a -->
|
||||
<!-- target="blank" -->
|
||||
<!-- href="https://leetcode.com/problems/boats-to-save-people/" -->
|
||||
<!-- >boats to save people</a -->
|
||||
<!-- > -->
|
||||
<!-- </h3> -->
|
||||
<h3>
|
||||
<a
|
||||
target="blank"
|
||||
href="https://leetcode.com/problems/boats-to-save-people/"
|
||||
>boats to save people</a
|
||||
>
|
||||
</h3>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
<!-- TODO: footnote -->
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>Finally, flesh out any remaining aspects of the implementation:</p>
|
||||
<ol>
|
||||
<li>If one person remains, give them a boat.</li>
|
||||
<li>
|
||||
If both people don't fit, use the heavier person—the
|
||||
lighter could maybe fit with someone else.
|
||||
</li>
|
||||
</ol>
|
||||
<div class="post-code">
|
||||
<pre><code class="language-python">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</code></pre>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</main>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue