Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Greedy

Boats to Save People

Medium · Greedy · Asked at Amazon, Google, Microsoft

Each boat carries at most two people and at most limit total weight. Every person weighs at most limit. Print the minimum number of boats needed to carry everyone.

Input

First line: n limit. Second line: the n weights.

Output

The minimum number of boats.

Constraints

Sort the weights. The heaviest person always takes a boat; if the lightest person fits with them, they go together. Two pointers from both ends.

Example 1

Input

4 3
3 2 2 1

Output

3

Example 2

Input

4 5
3 5 3 4

Output

4

Hints

  1. The heaviest person needs a boat no matter what.
  2. The best partner for them, if any, is the lightest person.
  3. Sort and use two pointers from both ends.

Approach

Sort the weights. With i at the lightest and j at the heaviest: the heaviest person always gets a boat (j−−); if the lightest fits with them (w[i] + w[j] ≤ limit), they share it (i++). Count one boat per step. If the lightest cannot fit with the heaviest, nobody can, so sending the heaviest alone loses nothing.

Complexity: O(n log n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, limit;
    cin >> n >> limit;
    vector<int> w(n);
    for (auto &x : w) cin >> x;
    sort(w.begin(), w.end());
    int i = 0, j = n - 1, boats = 0;
    while (i <= j) {
        if (w[i] + w[j] <= limit) i++;
        j--;
        boats++;
    }
    cout << boats << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, limit = data[0], data[1]
w = sorted(data[2 : 2 + n])
i, j, boats = 0, n - 1, 0
while i <= j:
    if w[i] + w[j] <= limit:
        i += 1
    j -= 1
    boats += 1
print(boats)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int limit = (int) in.nval;
        int[] w = new int[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            w[i] = (int) in.nval;
        }
        Arrays.sort(w);
        int i = 0, j = n - 1, boats = 0;
        while (i <= j) {
            if (w[i] + w[j] <= limit) i++;
            j--;
            boats++;
        }
        System.out.println(boats);
    }
}

Solve Boats to Save People online · All practice problems