Skip to content

Commit f1b8536

Browse files
committed
Add approach 2
1 parent b78bf1c commit f1b8536

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

problems/0011-container-with-most-water/container-with-most-water.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const maxArea = 最基本作法
22

3-
export default maxArea;
3+
export default 從兩側向內找高點;
44

55
/**
66
* 想不到有效加速法,先用最基本的做法
@@ -21,3 +21,26 @@ function 最基本作法(height: number[]): number {
2121

2222
return Math.max(...各座標作為左邊界的最大容積)
2323
}
24+
25+
/**
26+
* 依照 Approach 2: Two Pointer Approach 實作
27+
*
28+
* Result:
29+
* Runtime: 80 ms, faster than 95.78% of TypeScript online submissions
30+
* Memory Usage: 43.9 MB, less than 5.42% of TypeScript online submissions
31+
*/
32+
function 從兩側向內找高點(height: number[]): number {
33+
const 尋找最大容積 = (左側座標: number, 右側座標: number, max: number = 0): number => {
34+
if (左側座標 === 右側座標) return max
35+
36+
const 左高 = height[左側座標]
37+
const 右高 = height[右側座標]
38+
const 容積 = Math.min(左高, 右高) * (右側座標 - 左側座標)
39+
40+
return 左高 > 右高
41+
? 尋找最大容積(左側座標, 右側座標 - 1, Math.max(max, 容積))
42+
: 尋找最大容積(左側座標 + 1, 右側座標, Math.max(max, 容積))
43+
}
44+
45+
return 尋找最大容積(0, height.length - 1);
46+
}

0 commit comments

Comments
 (0)