Container with most water
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题其实可以直接用暴力解法求出答案。在高度未知的情况下,暂且可认为宽度越大,面积越大,所以可设左右两个指针,不断缩进,不断求出答案并比较,直到求出最优解
代码如下:
class Solution { public int maxArea(int[] height) { int length = height.length; int result = 0; int temp = 0; for(int i = 0; i < length - 1; i++) { for(int j = length - 1; j > i; j--) { if(height[i] > height[j]) { temp = height[j] * (j - i); if(temp > result) { result = temp; } } else { temp = height[i] * (j - i); if(temp > result) { result = temp; } } } } return result; } }