Skip to content

Commit

Permalink
leetcode: 881. Boats to Save People | Greedy | Two Pointers
Browse files Browse the repository at this point in the history
  • Loading branch information
ympons committed Jan 20, 2021
1 parent e1807d5 commit 9743a32
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
16 changes: 16 additions & 0 deletions leetcode/0881-boats-to-save-people/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 881. 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.*

**Example:**
```
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
```

**Constraints:**
- `1 <= people.length <= 5 * 10^4`
- `1 <= people[i] <= limit <= 3 * 10^4`
17 changes: 17 additions & 0 deletions leetcode/0881-boats-to-save-people/num_rescue_boats.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package leetcode

import "sort"

func numRescueBoats(people []int, limit int) int {
sort.Ints(people)
i, j := 0, len(people)-1
boats := 0
for i <= j {
if people[i]+people[j] <= limit {
i++
}
j--
boats++
}
return boats
}
36 changes: 36 additions & 0 deletions leetcode/0881-boats-to-save-people/num_rescue_boats_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package leetcode

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestNumRescueBoats(t *testing.T) {
assert := assert.New(t)
for _, test := range tests {
assert.Equal(test.expected, numRescueBoats(test.people, test.limit))
}
}

var tests = []struct {
people []int
limit int
expected int
}{
{
people: []int{1, 2},
limit: 3,
expected: 1,
},
{
people: []int{3, 2, 2, 1},
limit: 3,
expected: 3,
},
{
people: []int{3, 5, 3, 4},
limit: 5,
expected: 4,
},
}

0 comments on commit 9743a32

Please sign in to comment.