Problem: Problem - C1 - Codeforces
Hard Version : Problem - C2 - Codeforces
What’s the intution behind it and how to approach towards the solution for hard version? Any solution/logic with a brief explanation would help. Thank you.
Problem: Problem - C1 - Codeforces
Hard Version : Problem - C2 - Codeforces
What’s the intution behind it and how to approach towards the solution for hard version? Any solution/logic with a brief explanation would help. Thank you.
The basic logic behind it is that in the final answer, one element must be a peak (greater than or equal to previous element and also greater than or equal to next element) and elements before it should be in non-descending order and elements after it should be in non-ascending order.
For the easy version, we can just check by taking every element as a peak and then forming the solution. The answer is the solution with the largest total sum.
I have no idea how to solve the hard version.
for hard version during contest I overkilled with segment tree+binary search and got tle cz of high constant realize after contest a stack would suffice and there is no need of seg tree
Can you explain a bit more about the stack approach?
heres my code
#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
typedef long long int llo;
#define pb push_back
llo inf=100000000000;
#define mp make_pair
llo it[500001];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
llo n;
cin>>n;
for(llo i=0;i<n;i++){
cin>>it[i];
}
//build(0,0,n-1);
vector<pair<int,int>> stack;
int ll[n];
stack.pb(mp(it[0],0));
for(int i=1;i<n;i++){
while(stack.size()>0){
if(stack[stack.size()-1].first<=it[i]){
ll[i]=stack[stack.size()-1].second;
break;
}
else{
stack.pop_back();
}
}
stack.pb(mp(it[i],i));
}
int rr[n];
stack.clear();
stack.pb(mp(it[n-1],n-1));
for(int i=n-2;i>=0;i--){
while(stack.size()>0){
if(stack[stack.size()-1].first<=it[i]){
rr[i]=stack[stack.size()-1].second;
break;
}
else{
stack.pop_back();
}
}
stack.pb(mp(it[i],i));
}
llo l[n];
llo r[n];
l[0]=it[0];
llo maa=it[0];
for(llo i=1;i<n;i++){
if(maa>it[i]){
l[i]=(i+1)*it[i];
}
else{
llo ind=ll[i];
l[i]=l[ind]+(i-ind)*it[i];
}
maa=min(maa,it[i]);
}
r[n-1]=it[n-1];
maa=it[n-1];
for(llo i=n-2;i>=0;i--){
if(maa>it[i]){
r[i]=(n-i)*(it[i]);
}
else{
llo ind=rr[i];
r[i]=r[ind]+(ind-i)*it[i];
}
maa=min(maa,it[i]);
}
llo ans=0;
llo ans2=0;
for(llo i=0;i<n;i++){
if(l[i]+r[i]-it[i]>ans){
ans=l[i]+r[i]-it[i];
ans2=i;
}
}
llo arr[n];
arr[ans2]=it[ans2];
for(llo i=ans2-1;i>=0;i--){
arr[i]=min(it[i],arr[i+1]);
}
for(llo i=ans2+1;i<n;i++){
arr[i]=min(it[i],arr[i-1]);
}
for(llo i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}