Skip to content

Instantly share code, notes, and snippets.

Created March 13, 2017 10:34
Show Gist options
  • Select an option

  • Save anonymous/35e689eced61063639191adbbc42796f to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/35e689eced61063639191adbbc42796f to your computer and use it in GitHub Desktop.
def subset_sum(numbers, target, candidate=[], current=[])
candidate_sum = candidate.inject 0, :+
current_sum = current.inject 0, :+
if ( current_sum < candidate_sum && candidate_sum <= target ) ||
( current_sum == candidate_sum && current.length > candidate.length )
current = candidate
end
(0..(numbers.length - 1)).each do |i|
n = numbers[i]
remaining = numbers.drop(i+1)
current = subset_sum(remaining, target, candidate + [n], current)
end
current
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment