Created
April 28, 2013 07:17
-
-
Save hauntedhost/5476171 to your computer and use it in GitHub Desktop.
nearest_larger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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