Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions best-time-to-buy-and-sell-stock/han.exs
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions contains-duplicate/han.exs
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions two-sum/han.exs
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions valid-anagram/han.exs
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions valid-palindrome/han.exs
Original file line number Diff line number Diff line change
@@ -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