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.
贪心算法,一个指针在左,一个指针在右,向中间靠拢搜索。在靠拢的过程中,只找边越来越大的(因为距离越来越近了)。非常机智!
public class Solution {
public int maxArea(int[] height) {
if(height.length<2) return 0;
int max = Integer.MIN_VALUE;
int left =0, right = height.length-1;
while(left<=right){
max = Math.max(max, Math.min(height[left],height[right])* (right-left));
if(height[left]>=height[right]) right--;
else left++;
}
return max;
}
}
贪心算法的解释:即找局部最优。
顾名思义,贪心算法总是作出在当前看来最好的选择。也就是说贪心算法并不从整体最优考虑,它所作出的选择只是在某种意义上的局部最优选择。当然,希望贪心算法得到的最终结果也是整体最优的。虽然贪心算法不能对所有问题都得到整体最优解,但对许多问题它能产生整体最优解。如单源最短路经问题,最小生成树问题等。在一些情况下,即使贪心算法不能得到整体最优解,其最终结果却是最优解的很好近似。
推荐链接:
http://www.cnblogs.com/chinazhangjie/archive/2010/11/23/1885330.html