-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathWaterContainer.js
94 lines (71 loc) · 2.36 KB
/
WaterContainer.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
input: heights = [1,8,6,2,5,4,8,3,7]
Output: 49
*/
// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });
/* Brute Force Solution */
const getMaxWaterContainerBrute = function (heights) {
let maxArea = 0;
// Loop through the each points
for (let a1 = 0; a1 < heights.length; a1++) {
for (let a2 = a1 + 1; a2 < heights.length; a2++) {
const height = Math.min(heights[a1], heights[a2]);
const width = a2 - a1;
const area = height * width;
maxArea = Math.max(maxArea, area); // get the max area
}
}
console.log("Max water container can contain (Brute) - ", maxArea);
return maxArea;
};
/* Optimal Solution */
const getMaxWaterContainerOptimal = function (heights) {
let a1 = 0,
a2 = heights.length - 1,
maxArea = 0;
while (a1 < a2) {
const height = Math.min(heights[a1], heights[a2]);
const width = a2 - a1;
const area = height * width;
maxArea = Math.max(maxArea, area);
if (heights[a1] <= heights[a2]) {
a1++;
} else {
a2--;
}
}
console.log("Max water container can contain (optimal) - ", maxArea);
return maxArea;
};
// Take array length as input
let arrayLength = +prompt("Enter array length - ");
// Check whether the entered value is number or not
if (isNaN(arrayLength)) return console.log("Only numbers are allowed");
// Globally declared array
let array = [];
// Take array items
for (let i = 1; i <= arrayLength; i++) {
array.push(+prompt(`Enter ${i} element - `));
// Check whether the entered value is number or not
if (array.includes(NaN)) return console.log("Only numbers are allowed");
}
console.log("Your heights array - ", array);
// Call the algorithm
getMaxWaterContainerBrute(array);
getMaxWaterContainerOptimal(array);
/*
> node WaterContainer
Enter array length - 5
Enter 1 element - 4
Enter 2 element - 3
Enter 3 element - 2
Enter 4 element - 1
Enter 5 element - 4
Your heights array - [ 4, 3, 2, 1, 4 ]
Max water container can contain (Brute) - 16
Max water container can contain (optimal) - 16
*/