#K62667. Minimum Apples to Fill the Bag
Minimum Apples to Fill the Bag
Minimum Apples to Fill the Bag
You are given a number of apples, each with a specified weight. Your task is to determine the minimum number of apples required so that their total weight is at least a given capacity C. If it is impossible to reach or exceed the capacity using all the apples available, output -1
.
Mathematically, if the weights of the selected apples are \(w_1, w_2, \dots, w_k\), then you must have:
\(\sum_{i=1}^{k} w_i \ge C\)
The strategy is to use the heaviest apples first to achieve the capacity with the fewest apples.
inputFormat
The input is given through stdin and consists of two lines:
- The first line contains two integers n and C where n is the number of apples and C is the required bag capacity.
- The second line contains n space-separated integers representing the weights of the apples.
For example:
5 20 5 7 1 10 2
outputFormat
Output the minimum number of apples needed such that their total weight is at least C. Output -1
if it is not possible to achieve the required capacity.
The output should be written to stdout.
## sample5 20
5 7 1 10 2
3