Skip to content

Commit 66bba72

Browse files
committed
week6: container-with-most-water
1 parent 714782a commit 66bba72

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Brute Force
2+
// Time Complexity: O(n^2)
3+
// Space Complexity: O(1)
4+
const maxAreaBrute = (height) => {
5+
let maxWater = 0;
6+
for (let i = 0; i < height.length; i++) {
7+
for (let j = i + 1; j < height.length; j++) {
8+
const area = Math.min(height[i], height[j]) * (j - i);
9+
maxWater = Math.max(maxWater, area);
10+
}
11+
}
12+
return maxWater;
13+
};
14+
15+
// Two Pointer
16+
// Time Complexity: O(n)
17+
// Space Complexity: O(1)
18+
const maxArea = (height) => {
19+
let left = 0;
20+
let right = height.length - 1;
21+
let maxWater = 0;
22+
23+
while (left < right) {
24+
const area = Math.min(height[left], height[right]) * (right - left);
25+
26+
maxWater = Math.max(maxWater, area);
27+
28+
if (height[left] < height[right]) {
29+
left++;
30+
} else {
31+
right--;
32+
}
33+
}
34+
35+
return maxWater;
36+
};

0 commit comments

Comments
 (0)