Dsa
Greedy
Warm-up
Community Food Pantry
A community food pantry has received a donation of several snack bags of various weights. You are tasking with distributing these bags to a local shelter. However, your transport box has a strict weight limit W. You want to include as many individual snack bags as possible to ensure more people get a snack.
Input Format:
Line 1: An integer W representing the weight capacity of the box.
Line 2: A series of space-separated integers representing the weight of each snack bag.
Output Format:
Print a single integer representing the maximum number of snack bags that can fit in the box.
Example:
Input:
20
5 10 3 8 2
Output:
4
(Explanation: Choosing bags with weights 2, 3, 5, and 8 sums to 18, which is <= 20. Adding the 10 would exceed the limit.)
Key concepts
sortinggreedy
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now