- Boats to Save People
You are given an array people
where people[i]
is the weight of the ith
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.
- 对people进行排序,这里以升序为例,降序同理
- 如果
people[left] + people[right] > limit
,那么对任意的x > left,people[x] + people[right] > limit
都成立,此时right只能单独乘船 - 如果
people[left] + people[right] <= limit
,则left与right同乘
第3步的证明:
假设存在x > left使得x与right同乘优于left与right同乘
则必然存在y < right使得people[x] + people[y] > limit
且people[left] + people[y] <= limit
于是有people[x] + people[right] > people[x] + people[y] > limit
,这与x与right可以同乘矛盾
// runtime 90.84% memory 69.47%
var numRescueBoats = function(people, limit) {
people.sort((a, b) => a - b)
let left = 0
let right = people.length - 1
let res = 0
while (left < right) {
if (people[left] + people[right] <= limit) {
left++
}
right--
res++
}
if (left == right) {
res++
}
return res
}