Skip to content

Instantly share code, notes, and snippets.

@rtrv
Last active August 8, 2016 04:56
Show Gist options
  • Save rtrv/e3ae291313c3759b0202e9bdf2a8e440 to your computer and use it in GitHub Desktop.
Save rtrv/e3ae291313c3759b0202e9bdf2a8e440 to your computer and use it in GitHub Desktop.
Optimization of search the most remote similar elements in an array
=begin
# Original algorithm
def solution(a)
n = a.length
result = 0
for i in 0 .. (n - 1)
for j in 0 .. (n - 1)
if (a[i] == a[j]) then
if (i - j).abs > result then
result = (i - j).abs
end
end
end
end
return result
end
=end
=begin
# 30% optimized algorithm
def solution(a)
n = a.length
result = 0
for i in 0 .. (n - 1)
break if n - 1 - i <= result
for j in (n - 1) .. i
break if j - i <= result
if (a[i] == a[j]) then
if j - i > result then
result = j - i
end
end
end
end
return result
end
=end
# Last algorithm
def solution(a)
n = a.length
result = 0
h = {}
(0..n - 1).each do |i|
if h.key?(a[i])
result = i - h[a[i]] if i - h[a[i]] > result
else
# save first entry of every unique value
h[a[i]] = i
end
end
result
end
a = [1, 2, 3, 4, 5, 6, 7, 8, 4, 9, 10]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 3]
puts solution(a) # 5
puts solution(b) # 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment