guys here is the question which was asked yesterday on hackerearth : question
actually they haven’t released the editorial yet so can you help me with this . I am getting wrong answer .
here is the code :
#include <bits/stdc++.h>
using namespace std;
# define MOD 1000000009
# define pi 3.141593
template<class T> inline void read(T& x) {
char ch;
while(!isdigit(ch = getchar_unlocked()));
x = ch-'0';
while( isdigit(ch = getchar_unlocked())) x *= 10, x += ch-'0';
}
int main(){
long n;
cin >> n;
long a[n+2];
vector < pair <long,long> > b;
for(long i = 0 ; i < n ; i++){
cin >> a[i];
if(i != 0 && i != n-1){
b.push_back(make_pair(a[i],i));
}
}
sort(b.begin(),b.end());
long long answer = 0;
long index,left,right,left_index,right_index;
for(long i = 0 ; i < b.size() ; i++){
index = b[i].second;
a[index] = 0;
left_index = index-1;
right_index = index+1;
while(a[left_index] == 0){
left_index--;
}
while(a[right_index] == 0){
right_index++;
}
answer = answer + min(a[left_index],a[right_index]);
}
cout << answer;
return 0;
}