Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 565b22b

Browse files
doc: document algorithm
1 parent 9cbcc54 commit 565b22b

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed
Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,54 @@
11
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+
"""
213
left = 0
314
right = len(height) - 1
415
max_area = 0
516

617
while left < right:
18+
# Calculate the height and width of the current container
719
curr_height = min(height[left], height[right])
820
curr_width = right - left
921
curr_area = curr_height * curr_width
1022

23+
# Update max_area if the current area is larger
1124
max_area = max(curr_area, max_area)
1225

26+
# Move the pointer pointing to the shorter line
1327
if height[left] < height[right]:
1428
left += 1
1529
else:
1630
right -= 1
1731

1832
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /