I am trying to write an algorythm for a personnal project (just fun)

the algorythm goes like this. we have an array of random numbers:

[2, 32, 21, 5, 18, 18, 20, ...]

as you can see, the numbers vary and the size of the array vary. these are random numbers inputed by the user.

they CAN be repeated. in this example, 18 is repeated.

now. I have a maximum amount. let's say 50.

what I want to know is, how can I fit these numbers into 50, with having the least remainder possible.

so, I can have:

18,18,5,2 = 43

or

20,21,5,2 = 48

or

32, 18 = 50

I cannot go over the maximum amount...

I can add as many values as I want, without going over maximum (50 in this case)

in this example, 32,18 is the best since it hits exactly 50.

how would I go testing every combination efficiently? is there a quick way to find the best combination?

ideally, my goal is to repeat this process over and over until there are no numbers left in the array.

so once we find 23 and 18, we remove those and start over. perhaps 20,21,5,2 is the next best combination, we remove those and so on.

not sure how to start with this but wondering if some maths could be used to quickly find the most ideal combination fast?