← Back

Boats to Save People

Sort, then pair the lightest with the heaviest that still fits.

Medium LeetCode ↗ 1 / 1
func numRescueBoats(people []int, limit int) int {

}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)

    left, right := 0, len(people)-1
    boats := 0
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)

    left, right := 0, len(people)-1
    boats := 0

    for left <= right {

    }
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)

    left, right := 0, len(people)-1
    boats := 0

    for left <= right {
        // The heaviest person always boards. Take the lightest too if they fit.
    }
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)

    left, right := 0, len(people)-1
    boats := 0

    for left <= right {
        // The heaviest person always boards. Take the lightest too if they fit.
        if people[left]+people[right] <= limit {
            left++
        }
        right--
        boats++
    }
}
func numRescueBoats(people []int, limit int) int {
    // Micropattern: sort so we can pair extremes.
    sort.Ints(people)

    left, right := 0, len(people)-1
    boats := 0

    for left <= right {
        // The heaviest person always boards. Take the lightest too if they fit.
        if people[left]+people[right] <= limit {
            left++
        }
        right--
        boats++
    }

    return boats // O(n log n) for the sort, O(n) scan
}

Tap the left half to go back, the right half to go forward.

Arrow keys or space to navigate · Esc to exit.