Skip to content

Commit b13d233

Browse files
Jeehay28Jeehay28
authored andcommitted
Add container-with-most-water solution in TypeScript
1 parent 661204e commit b13d233

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// TC: O(n)
2+
// SC: O(1)
3+
4+
function maxArea(height: number[]): number {
5+
let left = 0;
6+
let right = height.length - 1;
7+
let maxWater = 0;
8+
9+
while (left < right) {
10+
const x = right - left;
11+
const y = Math.min(height[left], height[right]);
12+
13+
maxWater = Math.max(x * y, maxWater);
14+
15+
if (height[left] <= height[right]) {
16+
left += 1;
17+
} else {
18+
right -= 1;
19+
}
20+
}
21+
22+
return maxWater;
23+
}
24+
25+
26+
// ❌ Time Limit Exceeded!
27+
// TC: O(n^2)
28+
29+
// function maxArea(height: number[]): number {
30+
// // input: an integer array -> height
31+
// // output: the maximum amount of water
32+
// // height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
33+
34+
// let maxWater = 0;
35+
36+
// for (let start = 0; start < height.length - 1; start++) {
37+
// for (let end = start + 1; end < height.length; end++) {
38+
// const x = end - start;
39+
// const y = Math.min(height[start], height[end]);
40+
// maxWater = Math.max(maxWater, x * y);
41+
// }
42+
// }
43+
44+
// return maxWater;
45+
// }

0 commit comments

Comments
 (0)