Skip to content

Commit 563eb9a

Browse files
hh
h
authored and
h
committed
1 week answers
1 parent 2ab3667 commit 563eb9a

File tree

5 files changed

+60
-0
lines changed

5 files changed

+60
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
defmodule Solution do
2+
@spec max_profit(prices :: [integer]) :: integer
3+
def max_profit([head | tail]) do
4+
{_, answer} = Enum.reduce(tail, {head, 0}, fn x, {buy, profit} ->
5+
{min(buy, x), max(profit, x - buy)}
6+
end)
7+
8+
answer
9+
end
10+
end

contains-duplicate/han.exe

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
defmodule Solution do
2+
@spec contains_duplicate(nums :: [integer]) :: boolean
3+
def contains_duplicate(nums) do
4+
if nums |> Enum.into(MapSet.new) |> Enum.to_list |> length == length(nums) do
5+
false
6+
else
7+
true
8+
end
9+
end
10+
end

two-sum/han.exe

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
defmodule Solution do
2+
def two_sum([head | tail], target, index\\0) do
3+
second_index = Enum.find_index(tail, fn element ->
4+
head + element == target
5+
end)
6+
7+
if second_index, do: [index, second_index + index + 1], else: two_sum(tail, target, index + 1)
8+
end
9+
end

valid-anagram/han.exe

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
defmodule Solution do
2+
@spec is_anagram(s :: String.t, t :: String.t) :: boolean
3+
def is_anagram(s, t) do
4+
s |> String.split("", trim: true) |> Enum.sort == t |> String.split("", trim: true) |> Enum.sort
5+
end
6+
end

valid-palindrome/han.exe

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
defmodule Solution do
2+
@spec is_palindrome(s :: String.t) :: boolean
3+
def is_palindrome(s) do
4+
non_alphanumeric_ascii_codes = [?a..?z, ?0..?9] |>
5+
Enum.reduce([], fn x, acc ->
6+
acc ++ (x |> Enum.to_list)
7+
end)
8+
converted = s
9+
|> String.downcase
10+
|> String.replace(~r/./, fn char ->
11+
if :binary.first(char) in non_alphanumeric_ascii_codes, do: char, else: ""
12+
end)
13+
14+
length = converted |> String.length
15+
16+
if length < 2, do: true
17+
18+
center = length |> div(2)
19+
20+
converted |> String.slice(0..center) ==
21+
converted
22+
|> String.slice(-(center+1)..-1)
23+
|> String.reverse
24+
end
25+
end

0 commit comments

Comments
 (0)