How Many Apples Can You Put into the Basket
The problem is about finding out the maximum number of apples that can be carried in a basket. The basket has a weight limit of 5000 units.
The Python solution inside the provided class will be like this:
|
|
In this solution, we first initialize two variables: num_apples
to keep track of the number of apples we can carry, and total_weight
to keep track of the total weight of the apples we have decided to carry.
Next, we sort the weights of the apples in ascending order. This is because we want to fit as many apples as possible into the basket, and it makes sense to start with the lightest apples first.
After sorting the weights, we iterate over each apple. If the total weight of the apples we have chosen and the weight of the current apple is less than or equal to 5000 (the weight limit of the basket), we decide to carry the current apple: we add its weight to the total weight and increment num_apples
.
If the total weight of the apples we have chosen and the weight of the current apple exceeds 5000, we cannot carry the current apple, so we stop the loop.
Finally, we return num_apples
, the maximum number of apples that can be carried in the basket.