[leetcode]Container With Most Water
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.
题目描述:坐标轴n条与x轴垂直的线,求出由两条线围成的桶的最大面积。
算法思路:短板效应
1. 暴力法:求出所有两条线的组合情况,继而求出最大面积。
2. 二分法:维护一个最大面积,先算出首尾两条线组成的面积;然后让短板向中间走(因为长板向中间走只会让面积更小,只有更新短板才可能更新最大面积)
1 public class Solution { 2 public int maxArea(int[] height) { 3 if(height == null || height.length < 2) return 0; 4 int area = 0; 5 int begin = 0, end = height.length - 1,max = 0; 6 while(begin < end){ 7 int shortBar = Math.min(height[begin],height[end]); 8 area = shortBar * (end - begin); 9 if(area > max) { 10 max = area; 11 } 12 if(height[begin] == shortBar){ 13 begin++; 14 }else{ 15 end--; 16 } 17 } 18 return max; 19 } 20 }
参考:
http://blog.csdn.net/wzy_1988/article/details/17248209
http://www.cnblogs.com/zhaolizhen/p/Containerwater.html