zoukankan      html  css  js  c++  java
  • LeetCode "Container With Most Water"

    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.

  • 相关阅读:
    16款值得一用的iPhone线框图模板 (PSD & Sketch)
    设计神器
    {CF812}
    hiho1080(多标记线段树)
    {容斥原理}
    {dp入门}
    {AC自动机}
    CF807
    Trie树
    杂记
  • 原文地址:https://www.cnblogs.com/tonix/p/3916391.html
Copyright © 2011-2022 走看看