52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
from typing import List
|
|
|
|
test_array = [1, 8, 6, 2, 5, 4, 8, 3, 7]
|
|
|
|
|
|
# Brute force method
|
|
def max_area(height: List[int]) -> int:
|
|
heightest_water = 0
|
|
for first_position, first_height in enumerate(height):
|
|
for second_position, second_height in enumerate(height):
|
|
if first_position == second_position:
|
|
continue
|
|
else:
|
|
shortest_line = (
|
|
first_height if first_height < second_height else second_height
|
|
)
|
|
length = abs(first_position - second_position)
|
|
tmp_area = shortest_line * length
|
|
if tmp_area > heightest_water:
|
|
heightest_water = tmp_area
|
|
return heightest_water
|
|
|
|
|
|
# O(n) solution
|
|
# Here we are using two pointer method that shifts to each other depending on what
|
|
# pointer line is taller
|
|
def maxArea(height: List[int]) -> int:
|
|
# Initializing two pointers
|
|
res = 0
|
|
l, r = 0, len(height) - 1
|
|
# Program will work until pointers meet each other
|
|
while l < r:
|
|
# Calculating area between two pointers
|
|
# First multiplier is length between two lines
|
|
# Second multiplier is height of shortest lines of two
|
|
area = (r - l) * min(height[l], height[r])
|
|
# Set result for max of current max value and calculated area
|
|
res = max(res, area)
|
|
# Now after we calculated area we need to shift our left or right pointer
|
|
# If height of left line is more than heigh of right line
|
|
if height[l] < height[r]:
|
|
# That means that left pointer should be shifted
|
|
l += 1
|
|
elif height[l] > height[r]:
|
|
# Otherwise right pointer should be shifted
|
|
r -= 1
|
|
else:
|
|
# If they are equal => we dont care what pointer should be moved
|
|
r -= 1
|
|
# l +=1 both
|
|
return res
|
|
|