Skip to content

Commit 7287a87

Browse files
committed
Add container-with-most-water solution
1 parent 4d19c46 commit 7287a87

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} height
3+
* @return {number}
4+
*/
5+
6+
// Time Complexity: O(n)
7+
// Space Complexity: O(1)
8+
var maxArea = function (height) {
9+
let start = 0;
10+
let end = height.length - 1;
11+
let maxArea = 0;
12+
13+
while (start < end) {
14+
const area = (end - start) * Math.min(height[start], height[end]);
15+
maxArea = Math.max(area, maxArea);
16+
17+
// The shorter height limits the area.
18+
// By moving the pointer associated with the shorter height,
19+
// the algorithm maximizes the chance of finding a taller line that can increase the area.
20+
// This is the essence of the two-pointer strategy for the container problem.
21+
if (height[start] < height[end]) {
22+
start += 1;
23+
} else {
24+
end -= 1;
25+
}
26+
}
27+
return maxArea;
28+
};
29+

0 commit comments

Comments
 (0)