- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmost-water.ts
48 lines (38 loc) · 1.15 KB
/
most-water.ts
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
/**
* @description 盛水最多的容器
* @author tangc1
* @date 2022-07-01 16:07:45
*/
/**给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。画 n 条垂直线,使得垂直线 i 的两个
* 端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
*
* 你不能倾斜容器,n 至少是2。
*/
/**
* 双指针法
* 从头和尾开始
* 谁小谁向中间挪动
* 记录过程中盛水的最大值
*/
/**
* param { number[] } heightArr
* return { number }
*/
exportfunctionmaxArea(heightArr: number[]): number{
letresult=0
if(heightArr.length===0)returnresult
leti=0
letj=heightArr.length-1
while(i!==j){
letleft_height=heightArr[i]
letright_height=heightArr[j]
leth=Math.min(left_height,right_height)
result=Math.max(result,h*(j-i))
left_height>right_height ? j-- : i++
}
returnresult
}
// const arr1 = [1, 2, 3, 2, 1]
// const arr2 = [5, 2, 5, 2, 1]
// console.info(maxArea(arr1));
// console.info(maxArea(arr2));