Back to challenges
Hard 0 solved 0% acceptance

Minimum Elevator Rides

Group people into as few weight-limited elevator rides as possible.

What you'll learn

  • Represent groups of people as bitmasks
  • Store the best rides and last ride weight per subset
  • Handle exponential search spaces cleverly

Problem

Each person must ride exactly once. Any group can share a ride if the sum of its weights is no greater than capacity. People may be regrouped freely; their input order does not matter. Minimize the number of rides.

Implement elevator_rides(weights, capacity).

Input

weights: The weight of each person.

capacity: The maximum combined weight in a ride.

Output

Return the minimum number of rides.

Constraints

1 ≤ people ≤ 20. 1 ≤ capacity ≤ 1,000,000,000. Every weight is between 1 and capacity.

Examples

Example 1
Input:
weights = [3, 4, 5]
capacity = 7

Expected output:
expected = 2
Input:
std::vector<long long> weights = {3, 4, 5};
long long capacity = 7;

Expected output:
long long expected = 2;
Input:
long[] weights = new long[] {3, 4, 5};
long capacity = 7;

Expected output:
long expected = 2;

Explanation

Send 3 + 4 together and 5 separately. Total weight 12 cannot fit in one ride of capacity 7.

Example 2
Input:
weights = [2, 2, 2]
capacity = 6

Expected output:
expected = 1
Input:
std::vector<long long> weights = {2, 2, 2};
long long capacity = 6;

Expected output:
long long expected = 1;
Input:
long[] weights = new long[] {2, 2, 2};
long capacity = 6;

Expected output:
long expected = 1;

Explanation

All three people fit together because 2 + 2 + 2 = 6.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Since the number of people is small, consider subsets rather than individual rides.

Hint 2

Track both how many rides are used and how full the current last ride is for each subset.

Hint 3

When two states use the same number of rides, prefer the one with smaller current load.

Expected complexity

O(2^n * n) time, O(2^n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.