[模拟]LeetCode 11. Container With Most Water 题解

(传送门)
网络可能会不稳定……

题目大意

给出一个长度为n的数组a,求

min(ai,aj)×|ij| , 1i,jn


解题分析

真的要说能想出这个想法的都是神犇

终于找出Manchery搬来的题的原题了

貌似用各种神奇的扫描算法加排序可以防被卡?不自道啊。

标算其实很简单,首先先把ans求成L=1,R=n时的答案

然后找一下L,R中较小的那个,假设为L,那么指针k=L+1,k往R的方向移动,要找到一个比 aL 高的 ak ,因为L~k之间的值和L相比绝对不是更优的,比高度会降低min,比宽度又比不上L。只有找到比当初的高的才能在一个方面有优势,就有可能有更优解。然后L=k,重新比较L,R最后就会 L=R=amax ,这样减少了很多无用的比较,由于每个节点最多会被扫过一次,所以复杂度只有O(n);


复杂度:
时间: O(n)
空间: O(n)

#include<cstdio>
#include<algorithm>
using namespace std;
#define LL long long
int n,a[10000005]; LL ans;
inline void readi(int &x){
    x=0; char ch=getchar();
    while ('0'>ch||ch>'9') {ch=getchar();}
    while ('0'<=ch&&ch<='9') {x=x*10+ch-'0'; ch=getchar();}
}
int main()
{
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
    readi(n); for (int i=1;i<=n;i++) readi(a[i]);
    ans=(LL)min(a[1],a[n])*(n-1); int L=1,R=n;
    while (L<=R){
        if (a[L]<=a[R]){
            int k=L+1; while (k<=R&&a[k]<=a[L]) k++; L=k;
        }else{
            int k=R-1; while (L<=k&&a[k]<=a[R]) k--; R=k;
        }
        if (L<=R) ans=max(ans,(LL)min(a[L],a[R])*(R-L));
    }
    printf("%lld",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/try__jhf/article/details/78257641