leetcode:https://leetcode.com/problems/container-with-most-water/#/solutions
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.
Java Code:
package go.jacob.day618;
/**
* 11.Container With Most Water
* 算法复杂度O(n)
*
* @author Administrator 最大面积由较短边决定
*/
public class Demo1 {
public int maxArea(int[] height) {
if (height == null || height.length < 2)
return -1;
int left = 0, right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right]));
// 只要改变较短边的index
if (height[left] < height[right])
left++;
else
right--;
}
return maxArea;
}
}