zoukankan      html  css  js  c++  java
  • leetcode 11. Container With Most Water

    first, i use exhausitive search. however, it will exceed the time limit.

    int maxArea(vector<int>& height) {
            int n=height.size();
            int max=0;
            int s;
            for(int i=0;i<n;i++)
                for(int j=i+1;j<n;j++)
                {
                    //cout<< i<<endl;
                    //cout<<j<<endl;
                    //cout<<n<<endl;
                    int a=min(height[i],height[j]);
                    cout<<a<<endl;
                    s=(j-i)*a;
                    if(s>max)
                        max=s;
                }
            return max;
        }

    the time speed is O(n^2)

    then, i change the strategy. for impove the speed, I will search the vector from two direction. From the left to right and from right to left, until all the numbers has been checked.

    int maxArea(vector<int> & height)
        {
            int n=height.size();
            int max=0;
            int s;
            for(int i=0,j=n-1;i<j;)
            {
               s=(j-i)*min(height[i],height[j]);
                cout<< i<<endl;
                cout<<j<<endl;
                if(s>max)
                    max=s;
                if(height[i]>height[j])
                    j--;
                else
                    i++;
            }
            return max;
        }

    the intuition behind this approach is that we want to find the biggest two line to construct the container. because the area is decided by the shorter line.  To maximize the area, we need to consider the area between the lines of larger lengths. if we try to move the pointer at the longer line inwards, we won't gain any increase in area, since it is limited by the short line.O(n)

    if left > right, it means that we should find a biger left.

    if left <right, it means that we should find a biger left.

  • 相关阅读:
    subprocess使用小方法
    POJ3694 Network
    pickle 两个使用小方法
    软件补丁问题(SPFA+位运算)
    auto_ftp_sh
    幸运数字 容斥
    python调用脚本或shell的方式
    奇技淫巧
    运算符
    条件循环控制
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7202034.html
Copyright © 2011-2022 走看看