diff --git a/best-time-to-buy-and-sell-stock/han.exs b/best-time-to-buy-and-sell-stock/han.exs new file mode 100644 index 000000000..e404a0f45 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/han.exs @@ -0,0 +1,10 @@ +defmodule Solution do + @spec max_profit(prices :: [integer]) :: integer + def max_profit([head | tail]) do + {_, answer} = Enum.reduce(tail, {head, 0}, fn x, {buy, profit} -> + {min(buy, x), max(profit, x - buy)} + end) + + answer + end +end diff --git a/contains-duplicate/han.exs b/contains-duplicate/han.exs new file mode 100644 index 000000000..033dd6ca1 --- /dev/null +++ b/contains-duplicate/han.exs @@ -0,0 +1,10 @@ +defmodule Solution do + @spec contains_duplicate(nums :: [integer]) :: boolean + def contains_duplicate(nums) do + if nums |> Enum.into(MapSet.new) |> Enum.to_list |> length == length(nums) do + false + else + true + end + end +end diff --git a/two-sum/han.exs b/two-sum/han.exs new file mode 100644 index 000000000..138d4f61e --- /dev/null +++ b/two-sum/han.exs @@ -0,0 +1,9 @@ +defmodule Solution do + def two_sum([head | tail], target, index\\0) do + second_index = Enum.find_index(tail, fn element -> + head + element == target + end) + + if second_index, do: [index, second_index + index + 1], else: two_sum(tail, target, index + 1) + end +end diff --git a/valid-anagram/han.exs b/valid-anagram/han.exs new file mode 100644 index 000000000..e2f8d12ef --- /dev/null +++ b/valid-anagram/han.exs @@ -0,0 +1,6 @@ +defmodule Solution do + @spec is_anagram(s :: String.t, t :: String.t) :: boolean + def is_anagram(s, t) do + s |> String.split("", trim: true) |> Enum.sort == t |> String.split("", trim: true) |> Enum.sort + end +end diff --git a/valid-palindrome/han.exs b/valid-palindrome/han.exs new file mode 100644 index 000000000..c748d8753 --- /dev/null +++ b/valid-palindrome/han.exs @@ -0,0 +1,25 @@ +defmodule Solution do + @spec is_palindrome(s :: String.t) :: boolean + def is_palindrome(s) do + non_alphanumeric_ascii_codes = [?a..?z, ?0..?9] |> + Enum.reduce([], fn x, acc -> + acc ++ (x |> Enum.to_list) + end) + converted = s + |> String.downcase + |> String.replace(~r/./, fn char -> + if :binary.first(char) in non_alphanumeric_ascii_codes, do: char, else: "" + end) + + length = converted |> String.length + + if length < 2, do: true + + center = length |> div(2) + + converted |> String.slice(0..center) == + converted + |> String.slice(-(center+1)..-1) + |> String.reverse + end +end