I have a python list like the following:
sample_list = [20, 15, 35, 50, 2, 300, 225]
target_value = 200
Now, I want to write a python program that returns a list containing all the elements those total should be less than the target_value
and the closest value of target_value
. In the case of the mentioned example, the function should return the following list:
[20, 15, 35, 50, 2]
As 2+15+20+35+50 = 122
which is less than target_value = 200
but if I add any other value (300/225), it would be larger than 200.
I'm looking for a very optimized solution for this problem.