Skip to content

Commit c204b0b

Browse files
authored
Merge pull request #1440 from sounmind/main
[sounmind] WEEK 6 SOLUTIONS
2 parents d2cca9f + bbf5245 commit c204b0b

File tree

2 files changed

+62
-23
lines changed

2 files changed

+62
-23
lines changed

container-with-most-water/sounmind.js

-23
This file was deleted.

container-with-most-water/sounmind.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def maxArea(self, heights: List[int]) -> int:
6+
"""
7+
Find the maximum area that can form a container with the most water.
8+
9+
Problem: Given n non-negative integers representing heights of vertical lines,
10+
find two lines that together with the x-axis forms a container that holds the most water.
11+
12+
Approach:
13+
- Use two pointers technique starting from both ends of the array
14+
- Calculate area at each step and keep track of maximum
15+
- Move the pointer with smaller height inward (since it limits the container height)
16+
17+
Proof of correctness:
18+
- Every time we move a pointer, the width decreases by 1.
19+
- Why we move the pointer with smaller height:
20+
1) If we keep the smaller height and move the taller pointer instead,
21+
the width decreases but the height remains limited by the smaller value,
22+
so the area will always decrease.
23+
2) However, if we move the pointer with smaller height, we might find a taller line.
24+
In this case, even though width decreases, height might increase enough
25+
to create a larger area.
26+
- This way, we examine all possible combinations that could give us the maximum area.
27+
- We only explore combinations that have the potential to create an area larger
28+
than the maximum we've found so far.
29+
30+
Time Complexity: O(n) where n is the length of heights array
31+
Space Complexity: O(1) using constant extra space
32+
33+
Args:
34+
heights: List of heights of the vertical lines
35+
36+
Returns:
37+
Maximum water area that can be contained
38+
"""
39+
max_area = 0 # Initialize the maximum area to 0
40+
left, right = 0, len(heights) - 1 # Start with leftmost and rightmost positions
41+
42+
# Continue until the pointers meet
43+
while left < right:
44+
# Calculate width between current lines (difference in positions)
45+
width = right - left
46+
47+
# Height is limited by the shorter line
48+
current_height = min(heights[left], heights[right])
49+
50+
# Calculate current area and update max_area if larger
51+
current_area = width * current_height
52+
max_area = max(max_area, current_area)
53+
54+
# Move the pointer with smaller height inward
55+
# (Moving the smaller one gives potential for larger area since
56+
# width will decrease but height might increase)
57+
if heights[left] < heights[right]:
58+
left += 1
59+
else:
60+
right -= 1
61+
62+
return max_area

0 commit comments

Comments
 (0)