Skip to content

Commit fbea833

Browse files
committed
Add week 6 solutions : containerWithMostWater
1 parent 0d82c32 commit fbea833

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

container-with-most-water/yolophg.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
var maxArea = function(height) {
5+
let left = 0;
6+
let right = height.length - 1;
7+
8+
// to store the maximum area.
9+
let maxArea = 0;
10+
11+
// iterate until the two pointers meet.
12+
while (left < right) {
13+
// calculate the width between the two pointers.
14+
let width = right - left;
15+
16+
// calculate the area with the current area.
17+
let currentArea = Math.min(height[left], height[right]) * width;
18+
19+
// update the maximum area if the current area is larger.
20+
maxArea = Math.max(maxArea, currentArea);
21+
22+
// move the pointer to the shorter line towards the center.
23+
if (height[left] < height[right]) {
24+
left++;
25+
} else {
26+
right--;
27+
}
28+
}
29+
30+
// return the maximum area found.
31+
return maxArea;
32+
};

0 commit comments

Comments
 (0)