Skip to content

Commit d0e65f1

Browse files
author
konstantin
committed
Medium881 challenge
1 parent 1861e2d commit d0e65f1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package medium
2+
3+
import ArraysTopic
4+
import GreedyTopic
5+
import SortingTopic
6+
import TwoPointersTopic
7+
8+
/**
9+
* 881. Boats to Save People
10+
* https://leetcode.com/problems/boats-to-save-people/
11+
*
12+
You are given an array people where people[i] is the weight of the ith person,
13+
and an infinite number of boats where each boat can carry a maximum weight of limit.
14+
Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
15+
Return the minimum number of boats to carry every given person.
16+
*/
17+
18+
class Medium881 : ArraysTopic, TwoPointersTopic, GreedyTopic, SortingTopic {
19+
20+
fun numRescueBoats(people: IntArray, limit: Int): Int {
21+
people.sort()
22+
var result = 0
23+
for (i in people.indices) {
24+
if (people[i] == 0) continue
25+
for (j in people.lastIndex downTo i + 1) {
26+
if (people[j] == 0) continue
27+
if (people[j] + people[i] > limit) continue
28+
people[j] = 0
29+
break
30+
}
31+
people[i] = 0
32+
result++
33+
}
34+
return result
35+
}
36+
}
37+
38+
fun main() {
39+
println(Medium881().numRescueBoats(intArrayOf(1, 2), 3))
40+
println(Medium881().numRescueBoats(intArrayOf(3, 2, 2, 1), 3))
41+
println(Medium881().numRescueBoats(intArrayOf(3, 5, 3, 4), 5))
42+
println(Medium881().numRescueBoats(intArrayOf(5, 1, 4, 2), 6))
43+
}

0 commit comments

Comments
 (0)