Simply because I haven’t accounted for all the possible permutations that gets me the “closes possible result” to total, I simply went from the first element and move forward until you reach or pass total.
If you want a functionality like the one describing, that’s a whole lot more complicated to achieve, but I hope you got the logic, so you can work on it
Just for reference & to make it easier to Google, the general version of this is called the knapsack problem, and this specifically is called a subset sum problem. It’s a very common CS-related test question, it has many usecases in practice, and it’s quite hard to do efficiently. There is no [known] way to find a solution quickly for larger sets [bar throwing more computing power at it] regardless of the algorithm used because as the problem grows larger the time required to run the code expands rapidly.