Skip to content

Commit 983ddb4

Browse files
committed
container-with-most-water
1 parent 0e4f184 commit 983ddb4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 11. Container With Most Water
3+
* You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
4+
* Find two lines that together with the x-axis form a container, such that the container contains the most water.
5+
* Return the maximum amount of water a container can store.
6+
*
7+
* Notice that you may not slant the container.
8+
*
9+
* https://leetcode.com/problems/container-with-most-water/description/
10+
*
11+
*/
12+
13+
// O(n) time
14+
// O(1) space
15+
function maxArea(height: number[]): number {
16+
let l = 0;
17+
let r = height.length - 1;
18+
let max = 0;
19+
20+
while (l < r) {
21+
max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
22+
23+
if (height[l] < height[r]) {
24+
l++;
25+
} else {
26+
r--;
27+
}
28+
}
29+
30+
return max;
31+
}

0 commit comments

Comments
 (0)