mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
24 lines
664 B
Ruby
24 lines
664 B
Ruby
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
|