From c663927e3a3ebac710ab096943d66f27dc3c4f93 Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Thu, 15 Jan 2026 22:12:09 +0000 Subject: [PATCH] [Sync Iteration] elixir/knapsack/1 --- solutions/elixir/knapsack/1/lib/knapsack.ex | 23 +++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 solutions/elixir/knapsack/1/lib/knapsack.ex diff --git a/solutions/elixir/knapsack/1/lib/knapsack.ex b/solutions/elixir/knapsack/1/lib/knapsack.ex new file mode 100644 index 0000000..c103cbb --- /dev/null +++ b/solutions/elixir/knapsack/1/lib/knapsack.ex @@ -0,0 +1,23 @@ +defmodule Knapsack do + @doc """ + Return the maximum value that a knapsack can carry. + """ + @spec maximum_value(items :: [%{value: integer, weight: integer}], maximum_weight :: integer) :: integer + def maximum_value(items, maximum_weight), do: knapsack(items, maximum_weight, 0) + + # No items left + defp knapsack([], _, memo), do: memo + + # Item too heavy + defp knapsack([item | items], remaining_capacity, memo) when item.weight > remaining_capacity do + knapsack(items, remaining_capacity, memo) + end + + # Maxium between with and without the item + defp knapsack([item | items], remaining_capacity, memo) do + max( + knapsack(items, remaining_capacity - item.weight, memo + item.value), + knapsack(items, remaining_capacity, memo) + ) + end +end