# LeetCode 11. 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.
Note: You may not slant the container and n is at least 2.
Subscribe to see which companies asked this question.

Paste_Image.png

# 代码

``````public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
int computeArea(int left, int right,  int[] heights) {
return (right-left)*Math.min(heights[left], heights[right]);
}

public int maxArea(int[] heights) {
//两根指针，一头一尾计算，短的那根指针向中间移动，因为只有这种情况才存在更大的情况
int left = 0, right = heights.length-1;
int res = 0;

while(left < right) {
res = Math.max(res, computeArea(left,right,heights));
if(heights[left] < heights[right]) {
left++;
//如果小于则不必要计算，直接跳过
while(heights[left] <= heights[left-1] && left<right)
left++;
}
else {
right--;
while(heights[right] <= heights[right+1] && left <right)
right--;
}
}
return res;
}
}
``````
原文作者：六尺帐篷
原文地址: https://www.jianshu.com/p/3056972e1c92
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。