forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
11-Container-With-Most-Water.js
34 lines (26 loc) · 940 Bytes
/
11-Container-With-Most-Water.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* https://leetcode.com/problems/container-with-most-water/
* Time O(N) | Space(1)
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
let [left, right, max] = [0, height.length - 1, 0];
while (left < right) {
const [leftHeight, rightHeight] = getHeights(height, left, right);
const area = getArea(height, left, right);
max = Math.max(max, area);
const isRightGreater = leftHeight <= rightHeight;
if (isRightGreater) left++;
const isRightLess = rightHeight < leftHeight;
if (isRightLess) right--;
}
return max;
};
const getHeights = (height, left, right) => [height[left], height[right]];
const getArea = (height, left, right) => {
const [leftHeight, rightHeight] = getHeights(height, left, right);
const _height = Math.min(leftHeight, rightHeight);
const width = right - left;
return _height * width;
};