-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxWaterContainer.py
More file actions
38 lines (27 loc) · 1.18 KB
/
maxWaterContainer.py
File metadata and controls
38 lines (27 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def maxWaterContainer(height):
# Initialize two pointers at the beginning and end of the array
left, right = 0, len(height) - 1
# Variable to keep track of the maximum area found so far
max_area = 0
# Loop until the two pointers meet
while left < right:
# Height of the container is the shorter of the two lines
h = min(height[left], height[right])
# Width of the container is the distance between the two pointers
w = right - left
# Calculate the current area and update max_area if it's larger
max_area = max(max_area, h * w)
# Move the pointer pointing to the shorter line inward,
# since moving the taller one can't increase the area
if height[left] < height[right]:
left += 1 # Move left pointer to the right
else:
right -= 1 # Move right pointer to the left
# Return the maximum area found
return max_area
#Example Usage:
heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]
result = maxWaterContainer(heights)
print(result) # Output: 49
# Reference Hints & Solutions
# https://neetcode.io/solutions/container-with-most-water