Skip to content

Instantly share code, notes, and snippets.

@d12
Created January 2, 2022 16:23
Show Gist options
  • Save d12/f02350e8daa3a459c244e8ca7c6f0b0d to your computer and use it in GitHub Desktop.
Save d12/f02350e8daa3a459c244e8ca7c6f0b0d to your computer and use it in GitHub Desktop.
# Brute force
# Times out
# O(n^2) time, O(1) space
def max_area(heights)
max = 0
current_left_index = nil
current_right_index = nil
heights.each_with_index do |num1, index1|
next if num1 == 0
# Assuming we can find another pole with num1 height, how far out do we need to go for it to be worth it?
min_distance_2 = [index1 + 1, max / num1].max
heights[min_distance_2..-1]&.each_with_index do |num2, index2|
distance = min_distance_2 + index2 - index1
height = [num1, num2].min
if height * distance > max
max = height * distance
end
max = [max, height * distance].max
end
end
max
end
# 2 pointers
# O(N) time, O(1) space
def max_area(heights)
pointer_a = 0
pointer_b = heights.length - 1
max_area = 0
while pointer_a != pointer_b
height_a = heights[pointer_a]
height_b = heights[pointer_b]
distance = pointer_b - pointer_a
area = distance * [height_a, height_b].min
max_area = [max_area, area].max
if height_a < height_b
pointer_a += 1
else
pointer_b -= 1
end
end
max_area
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment