Skip to content

Instantly share code, notes, and snippets.

@psahni
Last active December 18, 2015 06:09
Show Gist options
  • Save psahni/5738134 to your computer and use it in GitHub Desktop.
Save psahni/5738134 to your computer and use it in GitHub Desktop.
Adjacent Element Distance.
class InvalidRange < Exception;end
class InvalidLength < Exception;end
@pairs_distance = {}
def solution(arr)
if ( (arr.min < -214748364) || (arr.max > 214748364) )
raise InvalidRange.new("Invalid Range")
end
if (arr.length > 40000)
raise InvalidLength.new("Invalid Length")
end
for i in 0..arr.length-2 do
for j in i+1..arr.length-1 do
find_adjacent(i, j, arr)
end
end
@pairs_distance
end
def find_adjacent(i, j, arr)
for k in 0..arr.length-1 do
if ( (arr[i] < arr[k]) && (arr[k] < arr[j]) || (arr[i] > arr[k]) && (arr[k] > arr[j]))
found = true
return # Found Something in between
else
found = false
next
end
end #for
if(k==arr.length-1 && found == false)
puts "(#{i}, #{j})"
distance = (arr[i]-arr[j]).abs
@pairs_distance[distance] = [i,j]
end
end
#0,1,2,3,4,5, 6, 7
arr = [0,3,3,7,5,3,11,1]
sol=
begin
solution(arr)
"The maximum distance is #{ @pairs_distance.keys.max } between indices #{ @pairs_distance[@pairs_distance.keys.max].inspect } "
rescue InvalidLength => e
-1
rescue InvalidLength => e
-2
end
p sol
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment