一个比较经典的题,可以序列分治或 st 表结合二分解决。这里用的是 st 表加二分。
钦定最大值显然是不好做的,考虑钦定 为次小值,st 表 + 二分可以确定最大值位置,复杂度 。
知道了最小值和次小值位置之后可以继续 st 表 + 二分去扩展最长的区间,这个复杂度是 的。
综上,时间复杂度 。
代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int M = 20;
const int N = 1e6 + 5;
int n, ans, a[N], L[N], R[N];
namespace ST {
int lg[N], st[N][M];
inline void init() {
for(int i = 2 ; i < N ; ++ i)
lg[i] = lg[i >> 1] + 1;
for(int i = 1 ; (1 << i) <= n ; ++ i)
for(int j = 1 ; j + (1 << i) - 1 <= n ; ++ j)
st[j][i] = min(st[j][i - 1], st[j + (1 << (i - 1))][i - 1]);
return ;
}
inline bool check(int x) {
if(x > n || x < 1) return true;
return false;
}
inline int query(int l, int r) {
if(l > r || check(l) || check(r)) return 1e18;
int k = lg[r - l + 1];
return min(st[l][k], st[r - (1 << k) + 1][k]);
}
}
using namespace ST;
inline int binary(int pos, int x) {
int l = 1, r = pos, mid = 0, res = pos;
while(l <= r) {
mid = (l + r) >> 1;
if(query(mid, pos - 1) >= x) r = mid - 1, res = mid;
else l = mid + 1;
}
return res;
}
inline int Binary(int pos, int x) {
int l = pos, r = n, mid = 0, res = pos;
while(l <= r) {
mid = (l + r) >> 1;
// cerr << l << ' ' << r << ' ' << pos + 1 << ' ' << mid << ' ' << query(pos + 1, mid) << ' ';
if(query(pos + 1, mid) >= x) l = mid + 1, res = mid;
else r = mid - 1;
// cerr << res << '\n';
}
return res;
}
inline int binaryy(int pos, int x) {
int l = 1, r = pos, mid = 0, res = pos;
while(l <= r) {
mid = (l + r) >> 1;
if(query(mid, pos - 1) <= x) l = mid + 1, res = mid;
else r = mid - 1;
}
if(a[res] > x) return pos;
else return res;
}
inline int Binaryy(int pos, int x) {
int l = pos, r = n, mid = 0, res = pos;
while(l <= r) {
mid = (l + r) >> 1;
if(query(pos + 1, mid) <= x) r = mid - 1, res = mid;
else l = mid + 1;
}
if(a[res] > x) return pos;
else return res;
}
signed main() {
ios_base :: sync_with_stdio(NULL);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n;
for(int i = 1 ; i <= n ; ++ i)
cin >> a[i], st[i][0] = a[i], L[i] = R[i] = i;
init();
// Binary(3, 3);
// return 0;
for(int i = 1 ; i <= n ; ++ i) {
int posx = binaryy(i, a[i]),
posl = binary(posx, a[i]),
posr = Binary(i, a[i]);
// if(i != posx) cerr << "i = " << i << " : " << posx << ' ' << posl << ' ' << posr << '\n';
if(i != posx) ans = max(ans, (a[i] + a[posx]) * (posr - posl + 1));
// if(ans == 30) cerr << "!!!" << i << ' ' << 1 << '\n';
posx = Binaryy(i, a[i]),
posl = binary(i, a[i]),
posr = Binary(posx, a[i]);
// if(i != posx) cerr << "i = " << i << " : " << posx << ' ' << posl << ' ' << posr << '\n';
if(i != posx) ans = max(ans, (a[i] + a[posx]) * (posr - posl + 1));
// if(ans == 30) cerr << "!!!" << i << ' ' << 2 << '\n';
}
cout << ans;
return 0;
}