Container with most water
Posted wakingshaw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于Container with most water的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode11-Container With Most Water