1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-18 21:56:57 +02:00
CodeWars/5kyu/best_travel/solution.rb
Matej Focko b4062b40c8
5kyu: add best travel
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 23:19:02 +01:00

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