11.盛水最多的容器
题目描述
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
示例
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
思路
左右两条边不断向中间推进,直到重合。取过程中的最大容量。
算法
1.l=0,r=length-1,max=0
2.比较l和r,当r大于l,执行3,否则执行5
3.max = max(max,l和r之间的容积)
4.l短则l++,r短则r- -,返回2
5.返回max
代码
class Solution {
public int maxArea(int[] height) {
int max =0 , l = 0, r = height.length-1;
while (r>l) {
if (height[l]>= height[r]){
max = Math.max(max,(r-l)* height[r]);
r --;
}else{
max = Math.max(max,(r-l)* height[l]);
l++;
}
}
return max;
}
}
执行效率
执行用时:3 ms, 在所有 Java 提交中击败了94.60%的用户
内存消耗:51.8 MB, 在所有 Java 提交中击败了44.63%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。