I am struggling with a fairly simple task that has an array of non-negative integers where I need to return the closest distance.
Array: arr = [8, 24, 3, 20, 1, 17]
Solution: 2 , arr[2]-arr[4]
Well, I managed to write a solution O (n ^ 2), which is clearly not enough.
def smallest_distance(a) result = nil a.each_with_index do |item1, index1| a.each_with_index do |item2, index2| next if index1 == index2 temp = (item1 - item2) >= 0 ? item1 - item2 : item2 - item1 result = temp if result.nil? || temp < result end end result end
Any ideas on how to improve this?
source share