1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-24 09:41:55 +01:00
CodeWars/5kyu/best_travel/solution.rb

25 lines
664 B
Ruby
Raw Permalink Normal View History

def choose_best_sum(t, k, ls)
def choose_best_sum_rec(max_total_distance, n, distances)
if n == 0 && max_total_distance >= 0 then
return 0
elsif max_total_distance < 0 || distances.size < 1 then
return nil
end
found = Array.new(2)
travelled = distances.pop
including_last = choose_best_sum_rec(max_total_distance - travelled, n - 1, distances)
if including_last != nil then
found[0] = including_last + travelled
end
found[1] = choose_best_sum_rec(max_total_distance, n, distances)
distances.push(travelled)
return found.select { |x| x != nil }.max
end
choose_best_sum_rec(t, k, ls.sort)
end