Container With Most Water - LeetCode

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值