Skip to content

ORIGINAL CODING QUESTION

Fewest shared cabs to the campus drive

Candidates travel to a campus drive in cabs. A cab carries one or two candidates, and their combined luggage weight must not exceed the limit. Every single candidate fits alone. Return the fewest cabs needed for everyone.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n limit, then n luggage weights.

Constraints

1 ≤ n ≤ 12; 1 ≤ weight ≤ limit ≤ 1000.

Example 1

Input

4 100 70 50 80 50

Output

3

The two 50s share a cab; 70 and 80 ride alone: three cabs.

Example 2

Input

3 10 5 5 5

Output

2

Two candidates share and the third rides alone.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

The heaviest candidate either rides alone or with someone light.

Hint 2

Sort the weights and use pointers at both ends.

Hint 3

Pair the heaviest with the lightest when they fit; otherwise the heaviest rides alone.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →