LeetCode 11. 盛最多水的容器
题目描述
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
我的写法
面积等于min(hieght[i],hight[j])*len 当len不断减小时,如果面积更大只能是高度变高,所以让i,j在头和尾然后向中靠拢,舍弃高度更小的,一直比较面积
public class LeetCode11 {
public static void main(String[] args) {
LeetCode11 lc11=new LeetCode11();
int height[]= {1,8,6,2,5,4,8,3,7};
System.out.println(lc11.maxArea(height));
}
public int maxArea(int[] height) {
int max=0;
int p=0;
int q=height.length-1;
int len;
while(p!=q) {
len=Math.min(height[p], height[q]);
max=Math.max(max, (q-p)*len);
if(height[p]>height[q]) {
q--;
}else {
p++;
}
}
return max;
}
}