题目链接
n <= 1e5 直接用分块优化,时间复杂度O(n^3/2)。不过正解是O(n)的算法,分块达到1e6的数据就不太方便了。
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x) & (-x))
typedef long long ll;
const int maxn = 1e6 + 7;
int a[maxn], block[maxn];
int ans[maxn];
inline int read(){
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if (ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = (x<<1) + (x<<3) + (ch^48);
ch = getchar();
}
return x * f;
}
int main(){
//ios::sync_with_stdio(false);
int n;
n = read();
int sz = sqrt(n);
for (int i = 1; i <= n; i ++){
block[i] = (i - 1) / sz + 1;
a[i] = read();
}
int num = n / sz;
if (n % sz != 0)
num ++;
for (int i = 1; i <= num; i ++){
ans[i] = 1000000000;
for (int j = 1 + sz * (i - 1); j <= min(sz * i,n); j ++)
ans[i] = min(ans[i],a[j]);
}
int cnt = 0;
for (int i = 1; i <= n; i ++){
int temp = 1000000000;
for (int j = block[i] + 1; j <= num; j ++)
temp = min(temp,ans[j]);
for (int j = i + 1; j <= min(sz * block[i],n); j ++)
temp = min(temp,a[j]);
cnt = max(cnt,a[i] - temp);
}
printf("%d\n",cnt);
return 0;
}