Skip to content

Latest commit

 

History

History
38 lines (33 loc) · 1.34 KB

2023-04-03.md

File metadata and controls

38 lines (33 loc) · 1.34 KB

Problem

  1. 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.

Intuition

  1. 对people进行排序,这里以升序为例,降序同理
  2. 如果people[left] + people[right] > limit,那么对任意的x > left,people[x] + people[right] > limit都成立,此时right只能单独乘船
  3. 如果people[left] + people[right] <= limit,则left与right同乘

第3步的证明: 假设存在x > left使得x与right同乘优于left与right同乘 则必然存在y < right使得people[x] + people[y] > limitpeople[left] + people[y] <= limit 于是有people[x] + people[right] > people[x] + people[y] > limit,这与x与right可以同乘矛盾

Code

// 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
}