Friday, May 3, 2019

Daily Coding Problem #291: Minimum Number of Boats to save population

Problem Definition

An imminent hurricane threatens the coastal town of Codeville. If at most two people can fit in a rescue boat, and the maximum weight limit for a given boat is k, determine how many boats will be needed to save everyone.

For example, given a population with weights [100, 200, 150, 80] and a boat limit of 200, the smallest number of boats required will be 3.

Solution

To be able to determine the smallest number of boats, we need to maximize the number of pairing. To maximize the number of pairing, for given weight we must pair with the maximum value possible. If we pair we smaller weight we may not get the minimum number.

For example, given a population with weights [30, 150, 170, 50] and a boat limit of 200. Here if we pair 30 with 50, then 150 and 170 are left alone hence resulting into the result 3. However, it is possible to pair 30 with 170 and 50 with 150 satisfying the constraint. This pairing will give the result 2.

Therefore, for each weight, we must pair it with the maximum weight possible. We might be tempted to use following solution:
  1. For each weight, iterate through rest of the weights to find the maximum weight with which it can be paired. Make sure to avoid already used weight.
This solution will work, but it will have time complexity $O(n^2)$

Solution Using Sorting

Following is implementation is using sorting. This method is still $O(n^2)$. It takes $O(n)$ time find pair. I am trying to figure out if the pair could be found in $O(logn)$ time instead so that the overall time complexity will be $O(nlogn)$

Implementation

Complexity

Sorting can be done in $O(n logn)$ time.
Finding a pair will take $O(n)$ time.

$\therefore$ The Time Complexity of this method will be $\cal{O(n^2)}$.






5 comments:

  1. Hi,
    Unfortunately your algorithm is wrong. Check this case:
    compute(new int[]{150, 150, 150, 30}, 200) - result of your algorithm is 2, but minimum number of boats are 3.

    You can benefit from sorting but still you'll have to iterate and do manual matching. Still complexity will be O(nlogn)

    ReplyDelete
    Replies
    1. Yes you are correct. My algorithm is not valid. Thank you for pointing this out.

      Delete
  2. i solve this recursively in python here:

    https://github.com/dlefcoe/daily-questions/blob/master/boatQuestion.py

    comments welcome.

    ReplyDelete
  3. Once the array is sorted, iterate through it starting from the largest value (O(n)). Then, for each large value, find the biggest value it can be paired with using binary search (O(log n)). This gives a complexity of O(nlogn).

    ReplyDelete