Max answer(单调栈+ST表)

Max answer

https://nanti.jisuanke.com/t/38228

Alice has a magic array. She suggests that the value of a interval is equal to the sum of the values in the interval, multiplied by the smallest value in the interval.

Now she is planning to find the max value of the intervals in her array. Can you help her?

Input

First line contains an integer n(1 \le n \le 5 \times 10 ^5n(1≤n≤5×105).

Second line contains nn integers represent the array a (-10^5 \le a_i \le 10^5)a(−105≤ai​≤105).

Output

One line contains an integer represent the answer of the array.

样例输入复制

5
1 2 3 4 5

样例输出复制

36

题意:给定n个数,求 区间最小值*区间和 的值最大

思路:先求前缀和,然后用st表求出区间最大最小值,再用单调栈求出每个数的左右边界,然后枚举最小值和它的区间和即可

 #include<bits/stdc++.h>
typedef long long ll;
using namespace std;
#define maxn 500005
int n;
ll sum[maxn],R[maxn],L[maxn],a[maxn],Max[maxn][],Min[maxn][]; ll queryMax(int x,int y){
int k=log2(y-x+);
return max(Max[x][k],Max[y-(<<k)+][k]);
} ll queryMin(int x,int y){
int k=log2(y-x+);
return min(Min[x][k],Min[y-(<<k)+][k]);
} int main(){
scanf("%d",&n);
for(int i=;i<=n;i++){
scanf("%lld",&a[i]);
sum[i]=sum[i-]+a[i];
Max[i][]=sum[i];
Min[i][]=sum[i];
}
for(int i=;i<;i++){
for(int j=;j+(<<i)-<=n;j++){
Max[j][i]=max(Max[j][i-],Max[j+(<<(i-))][i-]);
Min[j][i]=min(Min[j][i-],Min[j+(<<(i-))][i-]);
}
} stack<int>st;
for(int i=;i<=n;i++){
while(!st.empty()&&a[i]<=a[st.top()]){
st.pop();
}
if(st.empty()){
L[i]=;
}
else{
L[i]=st.top()+;
}
st.push(i);
}
while(!st.empty()) st.pop();
for(int i=n;i>=;i--){
while(!st.empty()&&a[i]<=a[st.top()]){
st.pop();
}
if(st.empty()){
R[i]=n;
}
else{
R[i]=st.top()-;
}
st.push(i);
}
ll ans=-0x3f3f3f3f3f3f3f3f;
for(int i=;i<=n;i++){
if(a[i]<){
ll minr=queryMin(i,R[i]);
ll maxl=queryMax(L[i]-,i);
ans=max(ans,(minr-maxl)*a[i]);
}
else if(a[i]>){
ll maxr=queryMax(i,R[i]);
ll minl=queryMin(L[i]-,i);
ans=max(ans,(maxr-minl)*a[i]);
}
else{
ans=max(ans,0LL);
}
}
printf("%lld\n",ans);
}
上一篇:SpringBoot实用小技巧之动态设置SpringBoot日志级别


下一篇:Mysql高手系列 - 第9篇:详解分组查询,mysql分组有大坑!