Skip to content

Instantly share code, notes, and snippets.

@hauntedhost
Created April 28, 2013 07:17
Show Gist options
  • Save hauntedhost/5476171 to your computer and use it in GitHub Desktop.
Save hauntedhost/5476171 to your computer and use it in GitHub Desktop.
nearest_larger
def left_match(arr, idx)
num = arr[idx]
unless idx.zero?
(idx - 1).downto(0) do |i|
return i if arr[i] > num
end
end
nil
end
def right_match(arr, idx)
num = arr[idx]
unless (idx == arr.size - 1)
(idx + 1).upto(arr.size - 1) do |i|
return i if arr[i] > num
end
end
nil
end
def nearest_larger(arr, idx)
num = arr[idx]
left = left_match(arr, idx)
right = right_match(arr, idx)
case
when left.nil? && right.nil?
nil
when left.nil?
right
when right.nil?
left
when arr[left] <= arr[right]
left
when arr[right] < arr[left]
right
else
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment