Added O(N) Solution with comments

This commit is contained in:
Jacob Delgado 2023-09-21 21:15:17 -07:00
parent d8d82396e3
commit f847a77884

View File

@ -3,20 +3,33 @@ def maxArea(height):
:type height: List[int] :type height: List[int]
:rtype: int :rtype: int
""" """
n = len(height) # n = len(height)
container = [] # container = []
# Handle edge-case # # Handle edge-case
if n == 2: # if n == 2:
return min(height) # return min(height)
for i in range(n): # for i in range(n):
for j in range(i+1,n): # for j in range(i+1,n):
index = min(height[i], height[j]) # index = min(height[i], height[j])
dist = j-i # dist = j-i
container.append(index*dist) # container.append(index*dist)
return max(container) # return max(container)
# return container # # return container
# Solution O(N) https://youtu.be/Kb20p6zy_14?si=6B86Iwh0-O_Cww0Q
max_area = 0
l = 0
r = len(height) - 1
while l < r:
area = (r - l) * min(height[r], height[l])
max_area = max(max_area, area)
if height[l] < height[r]: # Check to see if left or right is smaller
l += 1
else:
r -= 1
return max_area
print(maxArea([1,8,6,2,5,4,8,3,7])) #Output: 49 print(maxArea([1,8,6,2,5,4,8,3,7])) #Output: 49
print(maxArea([1,2,1])) #Output: 2 print(maxArea([1,2,1])) #Output: 2