Skip to content

Week 1 solutions - 김한기 #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 29, 2024
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