Skip to content

Instantly share code, notes, and snippets.

@vikas95prasad
Last active February 12, 2021 06:48
Show Gist options
  • Save vikas95prasad/d53be145d4166c57c0bd9a17029893b6 to your computer and use it in GitHub Desktop.
Save vikas95prasad/d53be145d4166c57c0bd9a17029893b6 to your computer and use it in GitHub Desktop.
Element with left side smaller and right side greater in Ruby
arr = [1,2,10,43,20,80,90]
maxArr = []
minArr = []
solution = [] #
large = arr[0] #first element
small = arr[-1] #last element
arr.each_with_index do |num, index|
if arr[index] > large
large = arr[index]
end
maxArr[index] = large
end
reverse_index = 5
arr.reverse_each do |num|
if arr[reverse_index] < small
small = arr[reverse_index]
end
minArr[reverse_index] = small
reverse_index -= 1
end
arr.each_with_index do |num, index|
# Skip first and last element if the array.
if index != 0 && index != (arr.size - 1)
if minArr[index] == maxArr[index]
solution << minArr[index]
end
end
end
puts solution
# Time Complexity => O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment