Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Last active November 13, 2024 05:26
Show Gist options
  • Save seanhandley/94f800afcd790839852c3b83c17cc23a to your computer and use it in GitHub Desktop.
Save seanhandley/94f800afcd790839852c3b83c17cc23a to your computer and use it in GitHub Desktop.
See Buildings to the Left
# Given a list of integers representing the heights of buildings,
# return the maximum number of buildings that can be seen when
# looking from the left. A building can see another building if
# it is taller than all the buildings to its left. The height of
# the tallest building is included in the count.
def see_buildings_left(buildings)
return 0 if buildings.empty?
buildings.each_cons(2).inject(1) do |count, (a, b)|
count += 1 if a < b
count
end
end
see_buildings_left([])
=> 0
see_buildings_left([1,2,3,4,5])
# => 5
see_buildings_left([5,4,3,2,1])
# => 1
see_buildings_left([3,7,8,3,6,1])
# => 3
see_buildings_left([1,1,2,2,2,2,6,3,1,10])
=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment