Buy the most appropriate items
Python 2, \$O(2^{n/2})\$
import sys
def subsetsum(nums, target):
# totalsum = sum(nums)
# if(totalsum == target):
# return target
# if(totalsum < target):
# return -1
sumsA = {}
sumsB = {}
for n in nums[::2]:
for k,v in sumsA.items() + [(0,[])]:
newsum = k + n
if newsum not in sumsA:
sumsA[newsum] = v + [n]
if newsum == target:
print "target found in sumsA loop: "
return target
minsum = sys.maxsize
for n in nums[1::2]:
for k,v in sumsB.items() + [(0,[])]:
newsum = k + n
if newsum not in sumsB:
sumsB[newsum] = v + [n]
if newsum == target:
print "target found in sumsB loop: "
return target
for a in sumsA:
combsum = a + newsum
if combsum == target:
print "target found in combined sumsA and sumsB loop: "
return target
if combsum > target and combsum < minsum:
minsum = combsum
print "target",target,"not found, so return the closest alternative: "
return minsum
# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)
Try it online.
My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.
The program uses the Knapsack Meet-in-the-middle approach. It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.