码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Container With Most Water" - GREEDY?

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

标签:des   style   blog   color   os   io   ar   div   

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?

标签:des   style   blog   color   os   io   ar   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!