Bessie's Weight Problem
InterviewTime limit1sMemory limit128 MB
Given N haybale weights and a limit H, find the largest total weight at most H that can be formed by choosing each bale at most once.
- Level
Medium4 of 10
- Topics
- Dynamic programming, Array, Brute force, Implementation
- Solved
- No attempts yet
Problem
Bessie the cow, like so many of her sisters, has put on a few pounds enjoying the delicious grass in Farmer John's pastures. Farmer John has now put her on a strict diet of no more than () kilograms of hay per day.
Bessie can eat only whole haybales: once she starts a bale she cannot stop, so she finishes it. She has a list of the () haybales available for tonight's dinner and, naturally, wants to maximize the total amount of hay she eats. She can eat each listed bale at most once. (Equal weights may appear several times in the list, and each such bale may be eaten once.)
Given the weights () of the haybales, determine the maximum total weight of hay Bessie can eat without exceeding her limit of kilograms.
Input
- Line 1: two space-separated integers and .
- Lines 2 to : line contains a single integer , the weight of haybale .
Output
- Line 1: a single integer, the maximum number of kilograms of hay Bessie can eat without going over her limit.
Hint
With four haybales of weight 15, 19, 20, and 21 and a limit of 56, Bessie can eat the bales weighing 15, 20, and 21 for a total of , reaching the limit exactly.