-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11-containerWithMostWater.js
46 lines (36 loc) · 1.01 KB
/
11-containerWithMostWater.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
35
36
37
38
39
40
41
42
43
44
45
// Brute force - O(n^2)
// var maxArea = function (height) {
// let result = 0;
// for (let i = 0; i < height.length; i++) {
// let intermediate = 0;
// for (let j = i + 1; j < height.length; j++) {
// let width = j - i;
// let length = Math.min(height[i], height[j]);
// let area = width * length;
// if (area > intermediate) {
// intermediate = area;
// }
// }
// if (intermediate > result) {
// result = intermediate;
// }
// }
// return result;
// };
// Two Pointer - O(n)
var maxArea = function (height) {
let maxArea = 0;
let i = 0;
let j = height.length - 1;
while (i !== j) {
let area = (j - i) * Math.min(height[i], height[j]);
if (area > maxArea) maxArea = area;
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return maxArea;
};
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]));