首页 > 其他 > 详细

LeetCode "Container With Most Water" - GREEDY?

时间:2014-08-16 15:04:30      阅读:276      评论:0      收藏:0      [点我收藏+]

O(n^2) is a naive solution. As rule of thumb, there must be O(n) soluion. Yes - Greedy.

We assume widest container contains the most water, greedily, but it is possible that we have higher heights with narrower range, so we proceed. Of course we disgard lower heights when shrinking window - we are greedy.

class Solution {
public:
    int maxArea(vector<int> &height)
    {
        size_t cnt = height.size();
        int i = 0, j = cnt - 1;

        int maxWater = std::numeric_limits<int>::min();

        while (i < j)
        {
            int minH = std::min(height[i], height[j]);
            maxWater = std::max(maxWater, minH * (j - i));

            if (height[i] <= height[j])
                while (height[++i] < minH && i < j);
            else
                while (height[j--] < minH && i < j);
        }

        return maxWater;
    }
};

As shown above, I did another small optimization: when window gets shrinked, we can skip all even-shorter heights.

LeetCode "Container With Most Water" - GREEDY?,布布扣,bubuko.com

LeetCode "Container With Most Water" - GREEDY?

原文:http://www.cnblogs.com/tonix/p/3916391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!