1
1
def max_area (height : list [int ]) -> int :
2
+ """
3
+ Calculate the maximum area of water a container can store, formed by two lines
4
+ from the given list of heights and the x-axis.
5
+
6
+ Parameters:
7
+ height (list[int]): A list of integers representing the heights of vertical lines.
8
+
9
+ Returns:
10
+ int: The maximum area of water that can be contained.
11
+
12
+ """
2
13
left = 0
3
14
right = len (height ) - 1
4
15
max_area = 0
5
16
6
17
while left < right :
18
+ # Calculate the height and width of the current container
7
19
curr_height = min (height [left ], height [right ])
8
20
curr_width = right - left
9
21
curr_area = curr_height * curr_width
10
22
23
+ # Update max_area if the current area is larger
11
24
max_area = max (curr_area , max_area )
12
25
26
+ # Move the pointer pointing to the shorter line
13
27
if height [left ] < height [right ]:
14
28
left += 1
15
29
else :
16
30
right -= 1
17
31
18
32
return max_area
19
-
33
+
34
+ # Approach and Reasoning:
35
+ # -----------------------
36
+ # - We use the two-pointer technique to solve this problem efficiently.
37
+ # - Initialize two pointers, `left` at the start and `right` at the end of the list.
38
+ # - The width of the container is the distance between the two pointers.
39
+ # - The height of the container is determined by the shorter of the two lines at the pointers.
40
+ # - Calculate the area for the current pair of lines and update `max_area` if this area is larger.
41
+ # - Move the pointer pointing to the shorter line inward to potentially find a taller line,
42
+ # which might result in a larger area.
43
+ # - Repeat the process until the two pointers meet.
44
+
45
+ # Time Complexity:
46
+ # ----------------
47
+ # - The time complexity of this approach is O(n), where n is the number of elements in the `height` list.
48
+ # - This is because each element is processed at most once as the pointers move towards each other.
49
+
50
+ # Space Complexity:
51
+ # -----------------
52
+ # - The space complexity is O(1) because we are using a constant amount of extra space,
53
+ # regardless of the input size.
54
+
0 commit comments