#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define all(a) a.begin(),a.end()
#define F first
#define S second
#define pb push_back
#define ll long long
#define vi vector<int>
#define pi pair<int,int>
#define mp make_pair

#ifdef LOCAL
string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(char ch) {
    return string("'")+ch+string("'");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <class InputIterator>
string to_string (InputIterator first, InputIterator last) {
    bool start = true;
    string res = "{";
    while (first!=last) {
        if (!start) {
            res += ", ";
        }
        start = false;
        res += to_string(*first);
        ++first;
    }
    res += "}";
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template<typename A,size_t N>
string to_string(A(&v)[N]){
    bool first = true;
    string res = "{";
    for (int i=0;i<N;i++) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template<size_t N>
string to_string(const bitset<N>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

string to_string(const vector<bool>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

void debug_out() {
    cerr << endl;
}

template <typename Head, typename... Tail>
void debug_out(Head&& H, Tail&&... T) {
    cerr << " " << to_string(forward<Head>(H));
    debug_out(forward<Tail>(T)...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

const int mod=1e9+7;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<typename A,typename B> istream& operator>>(istream&,pair<A,B>&);
template<typename A> istream& operator>>(istream&,vector<A>&);
void add(int&,int);
int mul(int,int);
int powz(int,int);
int sub(int,int);
template<typename A> ostream& operator<<(ostream&,vector<A>&);

const int N=500001;

int lef[N],rig[N],val[N];

void solve(){
    int n;
    cin>>n;
    vi a(n);
    cin>>a;
    debug(n);
    set<pair<int,int>>s;
    for(int i=0;i<n;i++){
        lef[i]=i-1;
        rig[i]=i+1;
        s.insert(mp(a[i],i));
    }
    int l=0,r=n-1;
    ll ans=0;
    int cnt=0;
    while(!s.empty()){
        cnt++;
        if(cnt>=n-1)break;
        auto it=s.begin();
        debug(s.size());
        pi val=*it;
        s.erase(val);
        int ind=val.S;
        if(ind==l){
            ans+=val.F;
            l=rig[ind];
            lef[rig[ind]]=ind;
            continue;
        }
        if(ind==r){
            ans+=val.F;
            rig[lef[ind]]=ind;
            r=lef[ind];
            continue;

        }
        ans+=min(a[lef[ind]],a[rig[ind]]);
        lef[rig[ind]]=lef[ind];
        rig[lef[ind]]=rig[ind];

    }
    cout<<ans;

}

signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int tc=1;
	//cin>>tc;
	for(int _=0;_<tc;_++){
		//cout<<"Case #"<<_+1<<": ";
		solve();
		if(_!=tc-1)
		cout<<"\n";
	}
}

int mul(int a,int b)
{
	return ((a)*1ll*(b))%mod;
}

void add(int &a,int b)
{
	a+=b;
	if(a>=mod)a-=mod;
}

int sub(int a,int b){
	a-=b;
	if(a<0){
		a+=mod;
	}
	return a;
}

int powz(int a,int b)
{
	int res=1;
	while(b)
	{
		if(b&1)res=mul(res,a);
		b/=2;
		a=mul(a,a);
	}
	return res;
}

template <typename A, typename B>
istream& operator>>(istream& input,pair<A,B>& x) {
	input>>x.F>>x.S;
	return input;
}

template <typename A>
istream& operator>>(istream& input,vector<A>& x) {
	for(auto& i:x)
		input>>i;
	return input;
}

template<typename A>
ostream& operator<<(ostream& output,vector<A>& x) {
	for(auto& i:x)
	    output<<i<<' ';
	return output;
}


#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define all(a) a.begin(),a.end()
#define F first
#define S second
#define pb push_back
#define ll long long
#define vi vector<int>
#define pi pair<int,int>
#define mp make_pair

#ifdef LOCAL
string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(char ch) {
    return string("'")+ch+string("'");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <class InputIterator>
string to_string (InputIterator first, InputIterator last) {
    bool start = true;
    string res = "{";
    while (first!=last) {
        if (!start) {
            res += ", ";
        }
        start = false;
        res += to_string(*first);
        ++first;
    }
    res += "}";
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template<typename A,size_t N>
string to_string(A(&v)[N]){
    bool first = true;
    string res = "{";
    for (int i=0;i<N;i++) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template<size_t N>
string to_string(const bitset<N>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

string to_string(const vector<bool>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

void debug_out() {
    cerr << endl;
}

template <typename Head, typename... Tail>
void debug_out(Head&& H, Tail&&... T) {
    cerr << " " << to_string(forward<Head>(H));
    debug_out(forward<Tail>(T)...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

const int mod=1e9+7;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<typename A,typename B> istream& operator>>(istream&,pair<A,B>&);
template<typename A> istream& operator>>(istream&,vector<A>&);
void add(int&,int);
int mul(int,int);
int powz(int,int);
int sub(int,int);
template<typename A> ostream& operator<<(ostream&,vector<A>&);

const int N=500001;

int lef[N],rig[N],val[N];

void solve(){
    int n;
    cin>>n;
    vi a(n);
    cin>>a;
    debug(n);
    set<pair<int,int>>s;
    for(int i=0;i<n;i++){
        lef[i]=i-1;
        rig[i]=i+1;
        if(i==0||i==n-1)continue;
        val[i]=min(a[i-1],a[i+1]);
        s.insert(mp(val[i],i));
    }
    ll ans=0;
    while(!s.empty()){
        auto it=s.end();
        it--;
        debug(s.size());
        pi val=*it;
        s.erase(val);
        int ind=val.S;
        ans+=val.F;
        if(lef[ind]!=-1&&lef[lef[ind]]!=-1&&rig[ind]!=n){
            s.erase(mp(min(a[lef[lef[ind]]],a[ind]),lef[ind]));
            s.insert(mp(min(a[lef[lef[ind]]],a[rig[ind]]),lef[ind]));
            rig[lef[ind]]=rig[ind];
        }
        if(rig[ind]!=n&&rig[rig[ind]]!=n&&lef[ind]!=-1){
            s.erase(mp(min(a[rig[rig[ind]]],a[ind]),rig[ind]));
            s.insert(mp(min(a[rig[rig[ind]]],a[lef[ind]]),rig[ind]));
            lef[rig[ind]]=lef[ind];
        }

    }
    cout<<ans;

}

signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int tc=1;
	//cin>>tc;
	for(int _=0;_<tc;_++){
		//cout<<"Case #"<<_+1<<": ";
		solve();
		if(_!=tc-1)
		cout<<"\n";
	}
}

int mul(int a,int b)
{
	return ((a)*1ll*(b))%mod;
}

void add(int &a,int b)
{
	a+=b;
	if(a>=mod)a-=mod;
}

int sub(int a,int b){
	a-=b;
	if(a<0){
		a+=mod;
	}
	return a;
}

int powz(int a,int b)
{
	int res=1;
	while(b)
	{
		if(b&1)res=mul(res,a);
		b/=2;
		a=mul(a,a);
	}
	return res;
}

template <typename A, typename B>
istream& operator>>(istream& input,pair<A,B>& x) {
	input>>x.F>>x.S;
	return input;
}

template <typename A>
istream& operator>>(istream& input,vector<A>& x) {
	for(auto& i:x)
		input>>i;
	return input;
}

template<typename A>
ostream& operator<<(ostream& output,vector<A>& x) {
	for(auto& i:x)
	    output<<i<<' ';
	return output;
}


#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define all(a) a.begin(),a.end()
#define F first
#define S second
#define pb push_back
#define ll long long
#define vi vector<int>
#define pi pair<int,int>
#define mp make_pair

#ifdef LOCAL
string to_string(string s) {
    return '"' + s + '"';
}

string to_string(const char* s) {
    return to_string((string) s);
}

string to_string(bool b) {
    return (b ? "true" : "false");
}

string to_string(char ch) {
    return string("'")+ch+string("'");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <class InputIterator>
string to_string (InputIterator first, InputIterator last) {
    bool start = true;
    string res = "{";
    while (first!=last) {
        if (!start) {
            res += ", ";
        }
        start = false;
        res += to_string(*first);
        ++first;
    }
    res += "}";
    return res;
}

template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}

template<typename A,size_t N>
string to_string(A(&v)[N]){
    bool first = true;
    string res = "{";
    for (int i=0;i<N;i++) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(v[i]);
    }
    res += "}";
    return res;
}

template<size_t N>
string to_string(const bitset<N>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

string to_string(const vector<bool>& v)
{
    string res="";
    for (int i = 0; i < (int)v.size(); ++i) {
        res+= char('0'+v[i]);
    }
    return res;
}

void debug_out() {
    cerr << endl;
}

template <typename Head, typename... Tail>
void debug_out(Head&& H, Tail&&... T) {
    cerr << " " << to_string(forward<Head>(H));
    debug_out(forward<Tail>(T)...);
}

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

const int mod=1e9+7;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<typename A,typename B> istream& operator>>(istream&,pair<A,B>&);
template<typename A> istream& operator>>(istream&,vector<A>&);
void add(int&,int);
int mul(int,int);
int powz(int,int);
int sub(int,int);
template<typename A> ostream& operator<<(ostream&,vector<A>&);

const int N=500001;

int lef[N],rig[N],val[N];

void solve(){
    int n;
    cin>>n;
    vi a(n);
    cin>>a;
    debug(n);
    set<pair<int,int>>s;
    for(int i=0;i<n;i++){
        lef[i]=i-1;
        rig[i]=i+1;
        s.insert(mp(a[i],i));
    }
    int l=0,r=n-1;
    ll ans=0;
    int cnt=0;
    while(!s.empty()){
        cnt++;
        if(cnt==n-1)break;
        auto it=s.begin();
        debug(s.size());
        pi val=*it;
        s.erase(val);
        int ind=val.S;
        if(ind==l){
            ans+=val.F;
            l=rig[ind];
            lef[rig[ind]]=ind;
            continue;
        }
        if(ind==r){
            ans+=val.F;
            rig[lef[ind]]=ind;
            r=lef[ind];
            continue;

        }
        ans+=min(a[lef[ind]],a[rig[ind]]);
        lef[rig[ind]]=lef[ind];
        rig[lef[ind]]=rig[ind];

    }
    cout<<ans;

}

signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int tc=1;
	//cin>>tc;
	for(int _=0;_<tc;_++){
		//cout<<"Case #"<<_+1<<": ";
		solve();
		if(_!=tc-1)
		cout<<"\n";
	}
}

int mul(int a,int b)
{
	return ((a)*1ll*(b))%mod;
}

void add(int &a,int b)
{
	a+=b;
	if(a>=mod)a-=mod;
}

int sub(int a,int b){
	a-=b;
	if(a<0){
		a+=mod;
	}
	return a;
}

int powz(int a,int b)
{
	int res=1;
	while(b)
	{
		if(b&1)res=mul(res,a);
		b/=2;
		a=mul(a,a);
	}
	return res;
}

template <typename A, typename B>
istream& operator>>(istream& input,pair<A,B>& x) {
	input>>x.F>>x.S;
	return input;
}

template <typename A>
istream& operator>>(istream& input,vector<A>& x) {
	for(auto& i:x)
		input>>i;
	return input;
}

template<typename A>
ostream& operator<<(ostream& output,vector<A>& x) {
	for(auto& i:x)
	    output<<i<<' ';
	return output;
}


#include <bits/stdc++.h>
using namespace std; bool ooo = 0; template <typename T> ostream& operator << (ostream& _o_, const vector <T> &_v_) { if(!_v_.empty()) {_o_ << '['; copy(_v_.begin(), _v_.end(), ostream_iterator <T> (_o_, ", ")); _o_ << "\b\b]"; } return _o_; } struct Dbg { template <typename T> Dbg& operator, (const T& v) { cout << v << ", "; return *this; } } Dbg; // struct _ { _() { ios_base::sync_with_stdio(0), cin.tie(0); } } _;
#define debug(args...)  if(ooo) { cout << #args << " = "; Dbg, args; cout << endl; }
#define int long long

const long long N = 5e5 + 5, mod = 998244353;

int n, ans = 0, mn = 0, a[N];
set <pair<int, int>> s;
vector <pair<int, int>> v;

signed main() {
	cin >> n;
	for(int i = 0; i < n; ++i) {
		cin >> a[i];
		s.insert({i, a[i]});
		v.push_back({a[i], i});
	}
	sort(v.begin(), v.end());
	for(int i = 0; i < n - 2; ++i) {
		ans += (v[i].first - mn) * (n - 2 - i);
		debug(v[i].first - mn, n - 2 - i);
		mn = v[i].first;
		set <pair<int, int>>::iterator it = s.find({v[i].second, v[i].first});
		if(it != s.begin() && ++it != s.end()) {
			int b = it->second;
			it--, it--;
			int a = it->second;
			ans += min(a, b) - mn;
		}
		s.erase({v[i].second, v[i].first});
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
using namespace std; bool ooo = 0; template <typename T> ostream& operator << (ostream& _o_, const vector <T> &_v_) { if(!_v_.empty()) {_o_ << '['; copy(_v_.begin(), _v_.end(), ostream_iterator <T> (_o_, ", ")); _o_ << "\b\b]"; } return _o_; } struct Dbg { template <typename T> Dbg& operator, (const T& v) { cout << v << ", "; return *this; } } Dbg; // struct _ { _() { ios_base::sync_with_stdio(0), cin.tie(0); } } _;
#define debug(args...)  if(ooo) { cout << #args << " = "; Dbg, args; cout << endl; }
// #define int long long

const long long N = 5e5 + 5, mod = 998244353;

int n, ans = 0, mn = 0, a[N];
set <pair<int, int>> s;
vector <pair<int, int>> v;

signed main() {
	cin >> n;
	for(int i = 0; i < n; ++i) {
		cin >> a[i];
		s.insert({i, a[i]});
		v.push_back({a[i], i});
	}
	sort(v.begin(), v.end());
	for(int i = 0; i < n - 2; ++i) {
		ans += (v[i].first - mn) * (n - 2 - i);
		debug(v[i].first - mn, n - 2 - i);
		mn = v[i].first;
		set <pair<int, int>>::iterator it = s.find({v[i].second, v[i].first});
		if(it != s.begin() && ++it != s.end()) {
			int b = it->second;
			it--, it--;
			int a = it->second;
			ans += min(a, b) - mn;
		}
		s.erase({v[i].second, v[i].first});
	}
	cout << ans << '\n';
}


#include <bits/stdc++.h>
using namespace std;

const int MN = 501234, INF = 1012345;
int a[MN];

set <pair <int, int> >::iterator minos(set <pair <int, int> >::iterator it) {
	it--;
	return it;
}

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	set <pair <int, int> > st, st2;
	for (int i = 0; i < n; i++)
		st.insert({a[i], i});
	for (int i = 0; i < n; i++)
		st2.insert({i, a[i]});
	int add = 0, ans = 0;
	while (st.size() > 2) {
		int x = st.begin()->first, y = st.begin()->second;
		st.erase(st.begin());
		st2.erase({y, x});
//		cerr << x;
//		cerr << x << ' ' << y << endl;
		if (st2.lower_bound({y, -1}) == st2.begin()) {
//			cerr << "here\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else if (st2.upper_bound({y, INF}) == st2.end()) {
//			cerr << "there\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else {
//			cerr << "NoWhere\n" << y << endl;
			ans += min(minos(st2.lower_bound({y, -1}))->second, st2.upper_bound({y, INF})->second) - add;
//			cerr << minos(st2.lower_bound({y, -1}))->second << ' ' << st2.upper_bound({y, INF})->second << endl;
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

const int MN = 501234, INF = 1012345;
int a[MN];

set <pair <int, int> >::iterator minos(set <pair <int, int> >::iterator it) {
	it--;
	return it;
}

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	set <pair <int, int> > st, st2;
	for (int i = 0; i < n; i++)
		st.insert({a[i], i});
	for (int i = 0; i < n; i++)
		st2.insert({i, a[i]});
	int add = 0, ans = 0;
	while (st.size() > 2) {
		int x = st.begin()->first, y = st.begin()->second;
		st.erase(st.begin());
		st2.erase({y, x});
//		cerr << x;
		cerr << x << ' ' << y << endl;
		if (st2.lower_bound({y, -1}) == st2.begin()) {
//			cerr << "here\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else if (st2.upper_bound({y, INF}) == st2.end()) {
//			cerr << "there\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else {
//			cerr << "NoWhere\n" << y << endl;
			ans += min(minos(st2.lower_bound({y, -1}))->second, st2.upper_bound({y, INF})->second) - add;
//			cerr << minos(st2.lower_bound({y, -1}))->second << ' ' << st2.upper_bound({y, INF})->second << endl;
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

#define int long long
const int MN = 501234, INF = 1012345;
int a[MN];

set <pair <int, int> >::iterator minos(set <pair <int, int> >::iterator it) {
	it--;
	return it;
}

int32_t main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	set <pair <int, int> > st, st2;
	for (int i = 0; i < n; i++)
		st.insert({a[i], i});
	for (int i = 0; i < n; i++)
		st2.insert({i, a[i]});
	int add = 0, ans = 0;
	while (st.size() > 2) {
		int x = st.begin()->first, y = st.begin()->second;
		st.erase(st.begin());
		st2.erase({y, x});
//		cerr << x;
//		cerr << x << ' ' << y << endl;
		if (st2.lower_bound({y, -1}) == st2.begin()) {
//			cerr << "here\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else if (st2.upper_bound({y, INF}) == st2.end()) {
//			cerr << "there\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else {
//			cerr << "NoWhere\n" << y << endl;
			ans += min(minos(st2.lower_bound({y, -1}))->second, st2.upper_bound({y, INF})->second) - add;
//			cerr << minos(st2.lower_bound({y, -1}))->second << ' ' << st2.upper_bound({y, INF})->second << endl;
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

const int MN = 501234, INF = 1012345;
int a[MN];

set <pair <int, int> >::iterator minos(set <pair <int, int> >::iterator it) {
	it--;
	return it;
}

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	set <pair <int, int> > st, st2;
	for (int i = 0; i < n; i++)
		st.insert({a[i], i});
	for (int i = 0; i < n; i++)
		st2.insert({i, a[i]});
	int add = 0, ans = 0;
	while (st.size() > 2) {
		int x = st.begin()->first, y = st.begin()->second;
		st.erase(st.begin());
		st2.erase({y, x});
//		cerr << x;
		cerr << x << ' ' << y << endl;
		if (st2.lower_bound({y, -1}) == st2.begin()) {
//			cerr << "here\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else if (st2.upper_bound({y, INF}) == st2.end()) {
//			cerr << "there\n";
			ans += (x - add) * (st.size() - 1);
			add = x;
		} else {
//			cerr << "NoWhere\n" << y << endl;
			ans += min(minos(st2.lower_bound({y, -1}))->second, st2.upper_bound({y, INF})->second) - add;
			cerr << minos(st2.lower_bound({y, -1}))->second << ' ' << st2.upper_bound({y, INF})->second << endl;
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 500005;

int n;
int a[N];

pair<int, int> b[N];

void solv()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    for (int i = 1; i <= n; ++i)
        b[i] = m_p(a[i], i);
    sort(b + 1, b + n + 1);
    set<int> s;
    for (int i = 1; i <= n; ++i)
        s.insert(i);
    ll ans = 0;
    int u = 0;
    for (int ii = 0; ii < n - 2; ++ii)
    {
        int i = b[ii + 1].se;
        if (i == *s.begin() || i == *(--s.end()))
        {
            ans += (n - 2 - ii) * 1LL * (a[i] - u);
            u = a[i];
        }
        else
        {
            int x1 = *s.upper_bound(i);
            int x0 = *(--s.find(i));
            ans += (n - 3 - ii) * 1LL * (a[i] - u);
            ans += min(a[x0] - u, a[x1] - u);
            u = a[i];
        }
        s.erase(i);
    }
    printf("%lld\n", ans);
}

int main()
{
    #ifdef SOMETHING
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #endif // SOMETHING
    //ios_base::sync_with_stdio(false), cin.tie(0);
    solv();
    return 0;
}

//while ((double)clock() / CLOCKS_PER_SEC <= 0.9){}


#include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 500005;

int n;
int a[N];

void solv()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    set<int> s;
    for (int i = 1; i <= n; ++i)
        s.insert(i);
    ll ans = 0;
    for (int ii = 0; ii < n - 2; ++ii)
    {
        int maxu = -1;
        int x;
        for (auto it = ++s.begin(); it != --s.end(); ++it)
        {
            --it;
            int x0 = *it;
            ++it;
            int x1 = *it;
            ++it;
            int x2 = *it;
            --it;
            if (min(a[x0], a[x2]) > maxu)
            {
                maxu = min(a[x0], a[x2]);
                x = x1;
            }
        }
        s.erase(x);
        ans += maxu;
    }
    printf("%lld\n", ans);
}

int main()
{
    #ifdef SOMETHING
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #endif // SOMETHING
    //ios_base::sync_with_stdio(false), cin.tie(0);
    solv();
    return 0;
}

//while ((double)clock() / CLOCKS_PER_SEC <= 0.9){}


#include <bits/stdc++.h>
using namespace std;
#define m_p make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
typedef long long ll;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 500005;

int n;
int a[N];

pair<int, int> b[N];

void solv()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    for (int i = 1; i <= n; ++i)
        b[i] = m_p(a[i], i);
    sort(b + 1, b + n + 1);
    set<int> s;
    for (int i = 1; i <= n; ++i)
        s.insert(i);
    ll ans = 0;
    int u = 0;
    for (int ii = 0; ii < n - 2; ++ii)
    {
        int i = b[ii + 1].se;
        if (i == *s.begin() || i == *(--s.end()))
        {
            ans += (n - 2 - ii) * 1LL * (a[i] - u);
            u = a[i];
        }
        else
        {
            int x1 = *s.upper_bound(i);
            int x0 = *(--s.find(i));
            //ans += (n - 3 - ii) * 1LL * (a[i] - u);
            ans += min(a[x0] - u, a[x1] - u);
        }
        s.erase(i);
    }
    printf("%lld\n", ans);
}

int main()
{
    #ifdef SOMETHING
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    #endif // SOMETHING
    //ios_base::sync_with_stdio(false), cin.tie(0);
    solv();
    return 0;
}

//while ((double)clock() / CLOCKS_PER_SEC <= 0.9){}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return 8*sizeof(int)-__builtin_clz(x); }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskC {
public:
void solve(istream& cin, ostream& cout) {
    int N; cin >> N;
    if (N <= 2) {
        cout << 0 << endl;
        return;
    }

    vector<int> A(N); cin >> A;
    vector<int> D;
    int M = 0;
    ll ans = 0;
    for (int i = 0; i < N; ++i) {
        while (M >= 2 && A[i] >= D[M-1] && D[M-2] >= D[M-1]) {
            ans += min(A[i], D[M - 2]);
            D.pop_back();
            M--;
        }

        D.push_back(A[i]);
        ++M;
    }

    bool isUp = true, isDown = true;
    ll sum = D[M-1];
    for (int i = 0; i < M-1; ++i) {
        isUp &= D[i] <= D[i+1];
        isDown &= D[i] >= D[i+1];
        sum += D[i];
    }

    if (isUp) {
        ans += sum - D[M-1] - D[M-2];
    } else if (isDown) {
        ans += sum - D[0] - D[1];
    } else {
        for (int i = 1; i < M-1; ++i) {
            ans += min(D[i-1], D[i+1]);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskC solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author majk
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T, typename U> std::ostream&operator<<(std::ostream&o, const pair<T,U>&p) {o << p.x << ' ' << p.y; return o;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {if(t.empty())o<<'\n';for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
ui logceil(int x) { return 8*sizeof(int)-__builtin_clz(x); }

namespace std { template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}}; }
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename F> double bshd(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){l=m;}else{h=m;}}return (l+h)/2;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename F> double bsld(double l,double h,const F&f,double p=1e-9){ui r=3+(ui)log2((h-l)/p);while(r--){double m=(l+h)/2;if(f(m)){h=m;}else{l=m;}}return (l+h)/2;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector2<T>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector2<T>>(a,vector2<T>(b,c,t)){}};
template<typename T>class vector4:public vector<vector3<T>>{public:vector4(){} vector4(size_t a,size_t b,size_t c,size_t d,T t=T()):vector<vector3<T>>(a,vector3<T>(b,c,d,t)){}};
template<typename T>class vector5:public vector<vector4<T>>{public:vector5(){} vector5(size_t a,size_t b,size_t c,size_t d,size_t e,T t=T()):vector<vector4<T>>(a,vector4<T>(b,c,d,e,t)){}};

#endif
// #include "../l/mod.h"

class TaskC {
public:
void solve(istream& cin, ostream& cout) {
    int N; cin >> N;
    if (N <= 2) {
        cout << 0 << endl;
        return;
    }

    vector<int> A(N); cin >> A;
    vector<int> D;
    int M = 0;
    ll ans = 0;
    for (int i = 0; i < N; ++i) {
        if (M >= 2 && A[i] >= D[M-1] && D[M-2] >= D[M-1]) {
            ans += min(A[i], D[M-2]);
            D[M-1] = A[i];
        } else {
            D.push_back(A[i]);
            ++M;
        }
    }

    bool isUp = true, isDown = true;
    ll sum = D[M-1];
    for (int i = 0; i < M-1; ++i) {
        isUp &= D[i] <= D[i+1];
        isDown &= D[i] >= D[i+1];
        sum += D[i];
    }

    if (isUp) {
        ans += sum - D[M-1] - D[M-2];
    } else if (isDown) {
        ans += sum - D[0] - D[1];
    } else {
        for (int i = 1; i < M-1; ++i) {
            ans += min(D[i-1], D[i+1]);
        }
    }

    cout << ans << endl;
}
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	TaskC solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define x first
#define y second
#define endl '\n'
#define mp make_pair
#define up_b upper_bound
#define low_b lower_bound
#define sz(x) (int)x.size()
#define bit __builtin_popcount
#define all(x) x.begin(),x.end()
#define show(x) cout<<(#x)<<" is "<<(x)<<endl

using namespace std;
using namespace __gnu_pbds;

template<typename T> using indexed_set=tree <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
typedef vector<vector<int>> matrix;

const ll INF=1e18+123;
const ld EPS=1e-9;
const int inf=1e9+123;
const int MOD=1e9+7;
const int N=5e5+123;
const int M=1e6+123;
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};

int a[N],v[N];

int main(){
    //ios_base::sync_with_stdio(0);
    //cin.tie(0);
    int n;
    cin>>n;
    indexed_set<int>ind;
    for(int i=1;i<=n;i++){
        scanf("%d",a+i);
        ind.insert(i);
    }
    multiset<pii>s;
    for(int i=2;i<n;i++){
        v[i]=min(a[i-1],a[i+1]);
        s.insert({v[i],i});
    }
    ll ans=0;
    while(ind.size()>2){
        pii x=*s.rbegin();
        s.erase(x);

        ans+=x.x;

        int k=ind.order_of_key(x.y);
        int i=*ind.find_by_order(k-1);
        int j=*ind.find_by_order(k+1);

        if(j<n){
            s.erase({v[j],j});
            int z=*ind.find_by_order(k+2);
        //    cout<<i<<" "<<j<<" "<<z<<endl;
            v[j]=min(a[i],a[z]);
            s.insert({v[j],j});
        }

        if(i>1){
            s.erase({v[i],i});
            int z=*ind.find_by_order(k-2);
            v[i]=min(a[z],a[j]);
            s.insert({v[i],i});
        }
        ind.erase(x.y);
    }
    cout<<ans;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define x first
#define y second
#define endl '\n'
#define mp make_pair
#define up_b upper_bound
#define low_b lower_bound
#define sz(x) (int)x.size()
#define bit __builtin_popcount
#define all(x) x.begin(),x.end()
#define show(x) cout<<(#x)<<" is "<<(x)<<endl

using namespace std;
using namespace __gnu_pbds;

template<typename T> using indexed_set=tree <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef pair<int,ll> pil;
typedef pair<ll,int> pli;
typedef vector<vector<int>> matrix;

const ll INF=1e18+123;
const ld EPS=1e-9;
const int inf=1e9+123;
const int MOD=1e9+7;
const int N=5e5+123;
const int M=1e6+123;
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};

int a[N];

int main(){
    //ios_base::sync_with_stdio(0);
    //cin.tie(0);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",a+i);
    }
    if(n==1){
        cout<<0;
        return 0;
    }
    ll ans=0;
    vector<int>v;
    v.push_back(a[1]);
    v.push_back(a[2]);
    for(int i=3;i<=n;i++){
        while(sz(v)>1){
            int x=v[sz(v)-2];
            int y=v.back();
            if(x>=y && y<=a[i]){
                v.pop_back();
                ans+=min(x,a[i]);
            }
            else break;
        }
        v.push_back(a[i]);
    }
    sort(all(v));
    for(int i=0;i+2<sz(v);i++){
        ans+=v[i];
    }
    cout<<ans;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/priority_queue.hpp>
//#pragma GCC optimize("O3")
//#pragma GCC target("sse4")
//#pragma GCC target("avx2")

#define deb(x) cout << #x << " = " << x << "\n"
#define all(x) (x).begin(), (x).end()
#define len(x) (ll) x.size()
#define lsb(x) (x) & -(x)
#define l(x) (x << 1) + 1
#define r(x) (x << 1) + 2
#define v(x) (ll)(x - 'a')

#define xx first
#define yy second
#define mp make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound

using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
typedef pair <ll, ll> pii;
typedef pair <ld, ld> pld;
typedef pair <ll, ll> pll;

template <class T1, class T2 = less <T1>> using pb_heap = __gnu_pbds::priority_queue <T1, T2, binary_heap_tag>;
template <class T1, class T2 = null_type, class T3 = less <T1>> using pb_map = tree <T1, T2, T3, rb_tree_tag, tree_order_statistics_node_update>;
template <class T1, class T2 = null_type, class T3 = hash <T1>> using pb_umap = gp_hash_table <T1, T2, T3>;
template <class T1, class T2, class T3 = hash <T1>> using umap = unordered_map <T1, T2, T3>;
template <class T> using uset = unordered_set <T>;
template <class T> using vec = vector <T>;

const ll infll = numeric_limits <ll>::max() >> 1;
const ll inf = numeric_limits <ll>::max() >> 1;
ll n, ans, lst, rem;

set <pii> elems;
map <ll, ll> value;

void input() {
    cin >> n;
    for(ll i = 1; i <= n; ++i) {
        ll x; cin >> x;
        elems.insert({x, i});
        value[i] = x;
    }
}

void erase(pii p) {
    ll num = p.xx - lst;
    ll ind = p.yy;
    auto it = value.ub(ind);
    ans += num * rem;
    lst += num;
    if(!(it == value.end() || prev(it) == value.begin())) {
        ans += min(it->yy, prev(prev(it))->yy) - lst;
    }
    rem--;
    value.erase(prev(it));
    elems.erase(p);
}

void solve() {
    lst = 0;
    ans = 0;
    rem = n - 2;
    for(ll i = 1; i <= n - 2; ++i) {
        erase(*elems.begin());
    }
    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    input();
    solve();
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<ll,ll> pll;
typedef vector<ii> vii;
typedef vector<ll> vll;
random_device device;
mt19937 generator(device());
uniform_int_distribution<int> get_random(0,10);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main()
{
	int n,i,x;ll ans=0ll;
	vi a;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&x);
		while(a.size()>=2&&a.back()<=x&&a.back()<=a[a.size()-2])
		{
			ans += (ll)min(a[a.size()-2],x);
			a.pop_back();
		}
		a.push_back(x);
	}
	for(i=1;i<a.size()-1;i++)
	{
		ans += (ll)min(a[i-1],a[i+1]);
	}
	printf("%lld",ans);
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<ll,ll> pll;
typedef vector<ii> vii;
typedef vector<ll> vll;
random_device device;
mt19937 generator(device());
uniform_int_distribution<int> get_random(0,10);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main()
{
	int n,i,x,ans=0;
	vi a;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&x);
		while(a.size()>=2&&a.back()<=x&&a.back()<=a[a.size()-2])
		{
			ans += min(a[a.size()-2],x);
			a.pop_back();
		}
		a.push_back(x);
	}
	for(i=1;i<a.size();i++)
	{
		ans += min(a[i-1],a[i+1]);
	}
	printf("%d",ans);
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<ll,ll> pll;
typedef vector<ii> vii;
typedef vector<ll> vll;
random_device device;
mt19937 generator(device());
uniform_int_distribution<int> get_random(0,10);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main()
{
	int n,i,x,ans=0;
	vi a;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&x);
		while(a.size()>=2&&a.back()<=x&&a.back()<=a[a.size()-2])
		{
			ans += min(a[a.size()-2],x);
			a.pop_back();
		}
		a.push_back(x);
	}
	for(i=1;i<a.size()-1;i++)
	{
		ans += min(a[i-1],a[i+1]);
	}
	printf("%d",ans);
}


#include <bits/stdc++.h>

using namespace std;

using ll = long long;
const int N = 500005;

int n, a[N], id[N];

int main() {
	scanf("%d", &n);
	for(int i = 0; i < n; i++) scanf("%d", a + i), id[i] = i;

	set<int> s(id, id + n);
	sort(id, id + n, [](int i, int j) {
		return a[i] < a[j];
	});

	ll ans = 0;
	int	del = 0;

	for(int w = 0; w + 2 < n; w++) {
		int i = id[w];
		int val = a[i] - del;
		auto it = s.find(i);
		ans += 1LL * (n - w - 2) * val;
		del += val;
		if(it != s.begin() and next(it) != s.end()) {
			int mn = min(a[*prev(it)], a[*next(it)]) - del;
			ans += mn;
		}
		s.erase(it);
	}

	printf("%lld\n", ans);
}


#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define sf scanf
#define pf printf
#define pb push_back
#define mp make_pair
#define PI ( acos(-1.0) )
#define IN freopen("C.in","r",stdin)
#define OUT freopen("output.txt","w",stdout)
#define FOR(i,a,b) for(i=a ; i<=b ; i++)
#define DBG pf("Hi\n")
#define i64 long long int
#define ui64 unsigned long long int
#define eps (1e-10)
#define neg first
#define pos second
#define ln 17
#define off 2

using namespace __gnu_pbds;
using namespace std ;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef tree< i64, null_type, less<i64>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef pair<int,int> pii;

#define mod 1000000007LL

#define maxn 200005
#define log 20

#define INF 1000000000000000000LL

int main()
{
    vector <int> v ;

    int n ;

    scanf("%d",&n) ;

    i64 ans = 0 ;

    for(int i=1 ; i<=n ; i++)
    {
        int a ;
        scanf("%d",&a) ;

        while( v.size() >= 2 && v.back() <= v[ v.size()-2 ] && v.back() <= a )
        {
            ans += min( a , v[ v.size()-2 ] ) ;
            v.pop_back() ;
        }
        v.pb(a) ;
    }

    for(int i=1 ; i+1<v.size() ; i++)
    {
        ans += min( v[i-1],v[i+1] ) ;
    }

    printf("%lld\n",ans) ;

    return 0 ;
}


// Remember...

#include<bits/stdc++.h>

#define F first
#define S second
#define PB push_back
#define sz(s) int((s).size())
#define bit(n,k) (((n)>>(k))&1)

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const int maxn=5e5+10,mod=1e9+7;
const ll inf=1e18;

vector<int> st, v1, v2;

int main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie();

    int n; cin>>n;
    ll ans=0;

    st.PB(0);
    for(int i=0;i<n;i++){
	int x; cin>>x;
	while(sz(st)>1 && st[sz(st)-2]>=st.back() && st.back()<=x) st.pop_back(),  ans+=min(x, st.back());
	st.PB(x);
    }
    st.PB(0);
    int pos=0;
    for(int i=0;i<sz(st);i++)
	if(st[pos]<=st[i]) pos=i;
    for(int i=0;i<=pos;i++)
	v1.PB(st[i]);
    for(int i=sz(st)-1;i>pos;i--)
	v2.PB(st[i]);
    int mx= st[pos], cnt=0;
    while(v1.back()==mx) v1.pop_back(), cnt++;

    while(sz(v1)>1 || sz(v2)>1){
	mx=max( v1.back(), v2.back() );
	while(v1.back()==mx) v1.pop_back(), cnt++;
	while(v2.back()==mx) v2.pop_back(), cnt++;
	ans+= cnt<2 ? 0 : 1ll*(cnt-2)*mx;
	cnt=min(cnt,2);
    }
    return cout<<ans<<endl,0;
}
// Deathly mistakes:
//  * Read the problem carefully.
//  * Check maxn.
//  * Overflows.

// #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")


//Be Name Khoda, Besmellah Rahmane Rahim, In The Name Of God;
//#include<bits/std++.h>
#include<iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <set>
#include <queue>
#include <deque>
#include <map>
#include <stack>
#include<bitset>
#include<list>
#include<cassert>
#include<numeric>
#include <stdio.h>
#include <string.h>
#include<iomanip>
#include<unordered_map>
#include<unordered_set>
#include <fstream>

using namespace std;

long long const N = 5e5 + 5;
long long n, ans;
long long a[N];
long long l[N];
long long r[N];
set <pair<long long, long long>> s;

int main()
{
    cin >> n;
    for (long long i = 1; i <= n; i ++)
    {
        cin >> a[i];
    }
    for (long long i = 0; i <= n + 1; i ++)
    {
        l[i] = i - 1;
        r[i] = i + 1;
    }

    for (long long i = 1; i <= n; i ++)
    {
        s.insert({a[i], i});
    }
    long long tmp = 0;
    while (s.size() > 2)
    {
        long long cnt = (*s.begin()).first - tmp;
        long long i = (*s.begin()).second;
        s.erase(s.begin());
        if (l[i] == 0)
        {
          tmp += cnt;
          ans += cnt * (s.size() - 1);
        }
        else
        {
            if (r[i] == n + 1)
            {
                tmp += cnt;
                ans += cnt * (s.size() - 1);
            }
            else
            {
                ans += min(a[l[i]] - tmp, a[r[i]] - tmp);
            }
        }
        l[r[i]] = l[i];
        r[l[i]] = r[i];
    }
    cout << ans << endl;
}


/*And I thought my jokes were bad*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg puts("Viva la vida");
#define CHECK(x) cout << (#x) << " is " << (x) << endl;
#define nl puts("");
#define mp make_pair
#define IN(x) scanf("%d",&x);
#define INL(x) scanf("%lld",&x);
#define OUT(x) printf("%d",x);
#define OUTL(x) printf("%lld",x);
#define MAX 1000005
#define MOD 1000000007
#define INF (1 << 31)
#define CASE(x,y) printf("Case %d: %d\n",++x,y);
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define PI acos(-1.0)
#define EPS 1e-19
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define int ll
/*
	when i get older
	i will be stronger
	they'll call me freedom
	just like a waving flag
*/
int arr[MAX],nxt[MAX],pre[MAX],n;
int vis[MAX];
queue<int> q;
void add(int i)
{
	if(i==0) return ;
	if(i==n+1) return ;
	if(vis[i]) return;

	if(arr[i]<=arr[pre[i]]&&arr[i]<=arr[nxt[i]])
	{
		q.push(i);
		vis[i]=1;
	}
}
void solve()
{
	int i,j,k,l,r,m,a,b,c,d,x,y,z,t;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		pre[i]=i-1;
		nxt[i]=i+1;
	}
	nxt[0]=1;
	pre[n+1]=n;

	for(i=1;i<=n;i++)
		add(i);
	int ans=0;
	while(!q.empty())
	{
		int cur=q.front();
		q.pop();
		ans+=min(arr[pre[cur]],arr[nxt[cur]]);
		nxt[pre[cur]]=nxt[cur];
		pre[nxt[cur]]=pre[cur];
		add(pre[cur]);
		add(nxt[cur]);

	}
	for(i=nxt[0];i<n+1;i=nxt[i])
	{
		ans+=min(arr[pre[i]],arr[nxt[i]]);
	}
	cout<<ans<<endl;
}

int32_t main()
{
	FASTIO
    int t=1;
    // cin>>t;
    while(t--) solve();
    return 0;
}


/*And I thought my jokes were bad*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg puts("Viva la vida");
#define CHECK(x) cout << (#x) << " is " << (x) << endl;
#define nl puts("");
#define mp make_pair
#define IN(x) scanf("%d",&x);
#define INL(x) scanf("%lld",&x);
#define OUT(x) printf("%d",x);
#define OUTL(x) printf("%lld",x);
#define MAX 1000005
#define MOD 1000000007
#define INF (1 << 31)
#define CASE(x,y) printf("Case %d: %d\n",++x,y);
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define PI acos(-1.0)
#define EPS 1e-19
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define int ll
/*
	when i get older
	i will be stronger
	they'll call me freedom
	just like a waving flag
*/
int arr[MAX],nxt[MAX],pre[MAX],n;
int vis[MAX];
queue<int> q;
void add(int i)
{
	if(i==0) return ;
	if(i==n+1) return ;
	if(vis[i]) continue;
	if(arr[i]<=arr[pre[i]]&&arr[i]<=arr[nxt[i]])
		q.push(i);
}
void solve()
{
	int i,j,k,l,r,m,a,b,c,d,x,y,z,t;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		pre[i]=i-1;
		nxt[i]=i+1;
	}
	nxt[0]=1;
	pre[n+1]=n;
	for(i=1;i<=n;i++)
		add(i);
	int ans=0;
	while(!q.empty())
	{
		int cur=q.front();
		vis[cur]=1;
		q.pop();
		ans+=min(arr[pre[cur]],arr[nxt[cur]]);
		nxt[pre[cur]]=nxt[cur];
		pre[nxt[cur]]=pre[cur];
		add(pre[cur]);
		add(nxt[cur]);
	}
	for(i=nxt[0];i<n+1;i=nxt[i])
	{
		ans+=min(arr[pre[i]],arr[nxt[i]]);
	}
	cout<<ans<<endl;
}

int32_t main()
{
	FASTIO
    int t=1;
    // cin>>t;
    while(t--) solve();
    return 0;
}


/*And I thought my jokes were bad*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg puts("Viva la vida");
#define CHECK(x) cout << (#x) << " is " << (x) << endl;
#define nl puts("");
#define mp make_pair
#define IN(x) scanf("%d",&x);
#define INL(x) scanf("%lld",&x);
#define OUT(x) printf("%d",x);
#define OUTL(x) printf("%lld",x);
#define MAX 200005
#define MOD 1000000007
#define INF (1 << 31)
#define CASE(x,y) printf("Case %d: %d\n",++x,y);
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define PI acos(-1.0)
#define EPS 1e-19
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define int ll
/*
	when i get older
	i will be stronger
	they'll call me freedom
	just like a waving flag
*/
int arr[MAX],nxt[MAX],pre[MAX],n;
queue<int> q;
void add(int i)
{
	if(i==0) return ;
	if(i==n+1) return ;
	if(arr[i]<=arr[pre[i]]&&arr[i]<=arr[nxt[i]])
		q.push(i);
}
void solve()
{
	int i,j,k,l,r,m,a,b,c,d,x,y,z,t;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		pre[i]=i-1;
		nxt[i]=i+1;
	}
	nxt[0]=1;
	pre[n+1]=n;
	for(i=1;i<=n;i++)
		add(i);
	int ans=0;
	while(!q.empty())
	{
		int cur=q.front();
		q.pop();
		ans+=min(arr[pre[cur]],arr[nxt[cur]]);
		nxt[pre[cur]]=nxt[cur];
		pre[nxt[cur]]=pre[cur];
		add(pre[cur]);
		add(nxt[cur]);
	}
	for(i=nxt[0];i<n+1;i=nxt[i])
	{
		ans+=min(arr[pre[i]],arr[nxt[i]]);
	}
	cout<<ans<<endl;
}

int32_t main()
{
	FASTIO
    int t=1;
    // cin>>t;
    while(t--) solve();
    return 0;
}


/*And I thought my jokes were bad*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg puts("Viva la vida");
#define CHECK(x) cout << (#x) << " is " << (x) << endl;
#define nl puts("");
#define mp make_pair
#define IN(x) scanf("%d",&x);
#define INL(x) scanf("%lld",&x);
#define OUT(x) printf("%d",x);
#define OUTL(x) printf("%lld",x);
#define MAX 1000005
#define MOD 1000000007
#define INF (1 << 31)
#define CASE(x,y) printf("Case %d: %d\n",++x,y);
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define PI acos(-1.0)
#define EPS 1e-19
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define int ll
/*
	when i get older
	i will be stronger
	they'll call me freedom
	just like a waving flag
*/
int arr[MAX],nxt[MAX],pre[MAX],n;
int vis[MAX];
queue<int> q;
void add(int i)
{
	if(i==0) return ;
	if(i==n+1) return ;
	if(vis[i]) return;
	vis[i]=1;
	if(arr[i]<=arr[pre[i]]&&arr[i]<=arr[nxt[i]])
		q.push(i);
}
void solve()
{
	int i,j,k,l,r,m,a,b,c,d,x,y,z,t;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		pre[i]=i-1;
		nxt[i]=i+1;
	}
	nxt[0]=1;
	pre[n+1]=n;

	for(i=1;i<=n;i++)
		add(i);
	int ans=0;
	while(!q.empty())
	{
		int cur=q.front();
		q.pop();
		ans+=min(arr[pre[cur]],arr[nxt[cur]]);
		nxt[pre[cur]]=nxt[cur];
		pre[nxt[cur]]=pre[cur];
		add(pre[cur]);
		add(nxt[cur]);
	}
	for(i=nxt[0];i<n+1;i=nxt[i])
	{
		ans+=min(arr[pre[i]],arr[nxt[i]]);
	}
	cout<<ans<<endl;
}

int32_t main()
{
	FASTIO
    int t=1;
    // cin>>t;
    while(t--) solve();
    return 0;
}


/*And I thought my jokes were bad*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg puts("Viva la vida");
#define CHECK(x) cout << (#x) << " is " << (x) << endl;
#define nl puts("");
#define mp make_pair
#define IN(x) scanf("%d",&x);
#define INL(x) scanf("%lld",&x);
#define OUT(x) printf("%d",x);
#define OUTL(x) printf("%lld",x);
#define MAX 500005
#define MOD 1000000007
#define INF (1 << 31)
#define CASE(x,y) printf("Case %d: %d\n",++x,y);
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define PI acos(-1.0)
#define EPS 1e-19
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define int ll
/*
	when i get older
	i will be stronger
	they'll call me freedom
	just like a waving flag
*/
int arr[MAX],nxt[MAX],pre[MAX],n;
queue<int> q;
void add(int i)
{
	if(i==0) return ;
	if(i==n+1) return ;
	if(arr[i]<=arr[pre[i]]&&arr[i]<=arr[nxt[i]])
		q.push(i);
}
void solve()
{
	int i,j,k,l,r,m,a,b,c,d,x,y,z,t;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>arr[i];
		pre[i]=i-1;
		nxt[i]=i+1;
	}
	nxt[0]=1;
	pre[n+1]=n;
	for(i=1;i<=n;i++)
		add(i);
	int ans=0;
	while(!q.empty())
	{
		int cur=q.front();
		q.pop();
		ans+=min(arr[pre[cur]],arr[nxt[cur]]);
		nxt[pre[cur]]=nxt[cur];
		pre[nxt[cur]]=pre[cur];
		add(pre[cur]);
		add(nxt[cur]);
	}
	for(i=nxt[0];i<n+1;i=nxt[i])
	{
		ans+=min(arr[pre[i]],arr[nxt[i]]);
	}
	cout<<ans<<endl;
}

int32_t main()
{
	FASTIO
    int t=1;
    // cin>>t;
    while(t--) solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,a[500010],b[500010],p=0;
long long ans;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		while(p>=2&&b[p-2]>=b[p-1]&&a[i]>=b[p-1]) ans+=min(b[p-2],a[i]),p--;
		b[p]=a[i];
		p++;
	}
	sort(b,b+p);
	for(int i=0;i<=p-3;i++) ans+=b[i];
	printf("%lld",ans);
	return 0;
}


#include<bits/stdc++.h>
int t,a,b,c,d;
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d%d%d",&a,&b,&c,&d);
		if ((a+b)&1)
			if ((b+c)&&(a+d)) printf("Ya Ya Tidak Tidak\n");
			else if (b+c) printf("Tidak Ya Tidak Tidak\n");
				 else printf("Ya Tidak Tidak Tidak\n");
		else
			if ((b+c)&&(a+d)) printf("Tidak Tidak Ya Ya\n");
			else if (b+c) printf("Tidak Tidak Ya Tidak\n");
				 else printf("Tidak Tidak Tidak Ya\n");
	 }
    return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	std::sort(st + 1, st + 1 + top);
	ans += std::accumulate(st + 1, st + 1 + std::max(1, top - 2), 0ll);
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	if (top > 2) {
		int l = std::max_element(st + 1, st + top + 1) - st, r = l;
		if (l != 1 && r != top)
			ans += std::min(st[--l], st[++r]);
		else if (r == top) --l;
		else ++r;
		while (l > 1 || r < top) {
			if (l > 1 && (r == top || st[l] > st[r]))
				ans += std::min(st[--l], st[r]);
			else
				ans += std::min(st[l], st[++r]);
		}
	}
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	if (top > 2) {
		int l = std::max_element(st + 1, st + top + 1) - st, r = l;
		if (l != 1 && r != n)
			ans += std::min(st[--l], st[++r]);
		else if (r == n) --l;
		else ++r;
		while (l > 1 || r < top) {
			if (l > 1 && (r == top || st[l] > st[r]))
				ans += std::min(st[--l], st[r]);
			else
				ans += std::min(st[l], st[++r]);
		}
	}
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	std::sort(st + 1, st + 1 + top);
	ans += std::accumulate(st + 1, st + 1 + std::max(0, top - 2), 0ll);
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	if (top > 2) {
		int l = std::max_element(st + 2, st + top) - st, r = l;
		ans += std::min(A[--l], A[++r]);
		while (l > 1 || r < top) {
			if (l > 1 && (r == top || A[l] > A[r]))
				ans += std::min(A[--l], A[r]);
			else
				ans += std::min(A[l], A[++r]);
		}
	}
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>

const int MAXN = 5e5 + 10;
typedef long long LL;
int A[MAXN], n;
int main() {
	std::cin >> n;
	LL ans = 0;
	static int st[MAXN], top;
	for (int i = 1; i <= n; ++i) {
		std::cin >> A[i];
		while (top > 1 && st[top - 1] >= st[top] && st[top] <= A[i])
			ans += std::min(st[--top], A[i]);
		st[++top] = A[i];
	}
	if (top > 2) {
		int l = std::max_element(st + 2, st + top) - st, r = l;
		ans += std::min(st[--l], st[++r]);
		while (l > 1 || r < top) {
			if (l > 1 && (r == top || st[l] > st[r]))
				ans += std::min(st[--l], st[r]);
			else
				ans += std::min(st[l], st[++r]);
		}
	}
	std::cout << ans << std::endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int n, u;
long long ans = 0;
vector<int> ve;

int main()
{
    cin >> n;
    while (n--)
    {
        cin >> u;
        while (ve.size() >= 2 && ve.back() <= min(ve[ve.size() - 2], u))
        {
            ans += min(ve[ve.size() - 2], u);
            ve.pop_back();
        }
        ve.push_back(u);
    }
    for (int i = 1; i < ve.size() - 1; i++)
        ans += min(ve[i - 1], ve[i + 1]);
    cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

int n, u;
long long ans = 0;
vector<int> ve;

int main()
{
    cin >> n;
    while (n--)
    {
        cin >> u;
        while (ve.size() >= 2 && ve.back() <= u)
        {
            ans += min(ve[ve.size() - 2], u);
            ve.pop_back();
        }
        ve.push_back(u);
    }
    for (int i = 2; i < ve.size(); i++)
        ans += ve[i];
    cout << ans;
}


#pragma GCC optimize(3,"Ofast","inline")
#pragma GCC target("avx,avx2")
#include <bits/stdc++.h>
using namespace std;
template<class t> inline t read(t &x){
	char c=getchar();bool f=0;x=0;
	while(!isdigit(c)) f|=c=='-',c=getchar();
	while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar();
	if(f) x=-x;return x;
}
template<class t,class ...A> inline void read(t &x,A &...a){
	read(x);read(a...);
}
template<class t> inline void write(t x){
	if(x<0) putchar('-'),write(-x);
	else{if(x>9) write(x/10);putchar('0'+x%10);}
}

const int N=5e5+5;
int x,s[N],top,ma1,ma2,n;
long long ans;

int min(int x,int y){
	return x<y?x:y;
}

signed main(){
	read(n);
	for(int i=1,x;i<=n;i++){
		read(x);
		while(top>1&&s[top]<=s[top-1]&&s[top]<=x) ans+=min(s[--top],x);
		s[++top]=x;
	}
	while(top){
		if(s[top]>ma1) ma2=ma1,ma1=s[top];
		else if(s[top]>ma2) ma2=s[top];
		ans+=s[top--];
	}
	write(ans-ma1-ma2);
}


#pragma GCC optimize(3,"Ofast","inline")
#pragma GCC target("avx,avx2")
#include <bits/stdc++.h>
using namespace std;
template<class t> inline t read(t &x){
	char c=getchar();bool f=0;x=0;
	while(!isdigit(c)) f|=c=='-',c=getchar();
	while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar();
	if(f) x=-x;return x;
}
template<class t,class ...A> inline void read(t &x,A &...a){
	read(x);read(a...);
}
template<class t> inline void write(t x){
	if(x<0) putchar('-'),write(-x);
	else{if(x>9) write(x/10);putchar('0'+x%10);}
}

const int N=5e5+5;
int x,s[N],top,ma1,ma2,n;
long long ans;

signed main(){
	read(n);
	for(int i=1,x;i<=n;i++){
		read(x);
		while(top>1&&s[top]<=s[top-1]&&s[top]<=x) ans+=min(s[--top],x);
		s[++top]=x;
	}
	while(top){
		if(s[top]>ma1) ma2=ma1,ma1=s[top];
		else if(s[top]>ma2) ma2=s[top];
		ans+=s[top--];
	}
	write(ans-ma1-ma2);
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 5e5+50;
int n, ans = 0;
int a[N];
pair<int,int> P[N];
int L[N], R[N];
#define fi first
#define se second
signed main(){
	cin >> n;
	for(int i=1;i<=n;i++){
		cin >> a[i];
		P[i] = {a[i],i};
	}
	sort(P+1,P+n+1);
	for(int i=1;i<=n;i++){
		L[i] = i-1;
		R[i] = i+1;
	}
	int l = 1, r = n;
	for(int i=1;i<=n-2;i++){
		int index = P[i].se;
		if(index==l){
			ans+=P[i].fi;
			l = R[l];
			continue;
		}
		if(index==r){
			ans+=P[i].fi;
			r = L[r];
			continue;
		}
		ans+=min(a[L[index]],a[R[index]]);
    	L[R[index]] = L[index];
    	R[L[index]] = R[index];
  	}
  	cout << ans << endl;
  	return 0;
}


#include <bits/stdc++.h>
#include <complex>
#include <queue>
#include <set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int,int> p32;
typedef pair<ll,ll> p64;
typedef pair<double,double> pdd;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<vector<int> > vv32;
typedef vector<vector<ll> > vv64;
typedef vector<vector<p64> > vvp64;
typedef vector<p64> vp64;
typedef vector<p32> vp32;
ll MOD = 1e9+7;
#define forn(i,e) for(ll i = 0; i < e; i++)
#define forsn(i,s,e) for(ll i = s; i < e; i++)
#define rforn(i,s) for(ll i = s; i >= 0; i--)
#define rforsn(i,s,e) for(ll i = s; i >= e; i--)
#define ln "\n"
#define dbg(x) cout<<#x<<" = "<<x<<ln
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF LLONG_MAX/2e5

ll mpow(ll a, ll b){
	if(b==0) return 1;
	ll t1 = mpow(a,b/2);
	t1 *= t1;
	t1 %= MOD;
	if(b%2) t1 *= a;
	t1 %= MOD;
	return t1;
}

void solve(){
	ll n;
	cin >> n;
	ll a[n];
	forn(i,n) cin >> a[i];
	ll nx[n],pr[n];
	forn(i,n) nx[i]=i+1;
	forn(i,n) pr[i]=i-1;
	set<p64> s;
	forn(i,n){
		s.insert(mp(a[i],i));
	}
	ll ans = 0;
	ll prev = 0;
	ll fact = n-2;
	for(auto it : s){
		if(fact<=0) break;
		ans += fact*(it.fi-prev);
		// cout << fact*(it.fi-prev) << ln;
		prev = it.fi;
		fact--;
		ll index = it.se;
		if(pr[index]!=-1) nx[pr[index]]=nx[index];
		if(nx[index]!=n) pr[nx[index]]=pr[index];
		if(pr[index]!=-1 && nx[index]!=n){
			ans += (min(a[pr[index]],a[nx[index]])-prev);
		}
	}
	cout << ans << ln;
}

int main()
{
	ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll t=1;
    // cin >> t;
    forn(i,t) {
    	solve();
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return 0;
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    for(int i = l + 1; i < r; i++){
        dp[l][r] = max(dp[l][r], get(l, i) + get(i, r) + min(a[l], a[r]));
    }

    return dp[l][r];
}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            dp[i][j] = -inf;
        }
    }

    cout << get(0, n - 1) << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return a[l] + a[r];
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    int el = -1;
    for(int i = l + 1; i < r; i++){
        int cur = get(l, i) + get(i, r) + min(a[l], a[r]);
        if(cur > dp[l][r]){
            dp[l][r] = cur;
            el = i;
        }
    }

    return dp[l][r];
}

//void show(int l, int r){
//    if(r - l == 0){
//        return;
//    }
//
//    int pos = -1;
//    for(int i = l + 1; i < r; i++){
//        if(dp[l][r] == get(l, i) + get(i, r) + min(a[l], a[r])){
//            pos = i;
//            break;
//        }
//    }
//
//    if(pos != -1){
//        cout << l << " " << pos << " " << pos << " " << r << "\n";
//        show(l, pos);
//        show(pos, r);
//    }
//}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    ll ans = 0;
    stack<int> s;
    for(int i = 0; i < n; i++){
        while(s.size() >= 2){
            int top = s.top();
            s.pop();

            if(s.top() < top || top > a[i]){
                s.push(top);
                break;
            }

            ans += min(s.top(), a[i]);
        }
        s.push(a[i]);
    }

    int *end = &s.top() + 1;
    int *begin = end - s.size();
    vector<int> b(begin, end);

    for(int i = 1; i < b.size() - 1; i++){
        ans += min(b[i - 1], b[i + 1]);
    }
    cout << ans << "\n";
}

/*
10
96 66 8 18 30 48 34 11 37 42

4
96 66 48 42
*/


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return a[l] + a[r];
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    int el = -1;
    for(int i = l + 1; i < r; i++){
        int cur = get(l, i) + get(i, r) + min(a[l], a[r]);
        if(cur > dp[l][r]){
            dp[l][r] = cur;
            el = i;
        }
    }

    return dp[l][r];
}

//void show(int l, int r){
//    if(r - l == 0){
//        return;
//    }
//
//    int pos = -1;
//    for(int i = l + 1; i < r; i++){
//        if(dp[l][r] == get(l, i) + get(i, r) + min(a[l], a[r])){
//            pos = i;
//            break;
//        }
//    }
//
//    if(pos != -1){
//        cout << l << " " << pos << " " << pos << " " << r << "\n";
//        show(l, pos);
//        show(pos, r);
//    }
//}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    ll ans = 0;
    stack<int> s;
    for(int i = 0; i < n; i++){
        while(s.size() >= 2){
            int top = s.top();
            s.pop();

            if(s.top() < top || top > a[i]){
                s.push(top);
                break;
            }

            ans += min(s.top(), a[i]);
        }
        s.push(a[i]);
    }

    int *end = &s.top() + 1;
    int *begin = end - s.size();
    vector<int> b(begin, end);

    int cur = 0;
    int l = 0;
    int r = b.size() - 1;
    while(l < r - 1){
        ans += (min(a[l], a[r]) - cur + 0ll) * (r - l - 1);
        cur = min(a[l], a[r]);
        if(a[l] <= a[r]){
            ++l;
        } else {
            --r;
        }
    }

    cout << ans << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int inf = 2000000000;
const int N = 1e5 + 5;

int n, a[N];

int checkOrder(vector<int>& b){
    set<int> s;
    for(int i = 0; i < n; i++){
        s.insert(i);
    }
    int ans = 0;
    for(auto val : b){
        auto it = s.upper_bound(val);
        int next = *it;
        int prev = *(----it);
        ans += min(a[next], a[prev]);
        s.erase(val);
    }
    return ans;
}
int solveStupid(){
    vector<int> b;
    for(int i = 1; i < n - 1; i++){
        b.pb(i);
    }

    int ans = checkOrder(b);
    while(next_permutation(b.begin(), b.end())){
        ans = max(ans, checkOrder(b));
    }
    return ans;
}

int getNext(int pos, bool use[]){
    for(int i = pos + 1; i < n; i++){
        if(!use[i]){
            return a[i];
        }
    }
}
int getPrev(int pos, bool use[]){
    for(int i = pos - 1; i >= 0; i--){
        if(!use[i]){
            return a[i];
        }
    }
}
int f(int pos, bool use[]){
    return min(getNext(pos, use), getPrev(pos, use));
}
int solveGreed(){
    bool use[n];
    memset(use, false, sizeof(use));

    int ans = 0;
    for(int i = 0; i < n - 2; i++){
        int cur = inf, pos = -1, ttmp = 0;
        for(int j = 1; j < n - 1; j++){
            if(!use[j]){
                int tmp = f(j, use);
                if(a[j] < cur || (a[j] == cur && tmp > ttmp)){
                    cur = a[j];
                    ttmp = tmp;
                    pos = j;
                }
            }
        }

        use[pos] = true;
        ans += f(pos, use);
    }
    return ans;
}

main(){
    srand(time(NULL));
    cin.tie(0);
    ios_base::sync_with_stdio(0);

//    cin >> n;
//    n = rand() % 10 + 2;
//    cout << n << "\n";
//    for(int i = 0; i < n; i++){
//        cin >> a[i];
//        a[i] = rand() % 1000;
//        cout << a[i] << " ";
//    }
//    cout << "\n";

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    cout << solveStupid() << " " << solveGreed() << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return a[l] + a[r];
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    int el = -1;
    for(int i = l + 1; i < r; i++){
        int cur = get(l, i) + get(i, r) + min(a[l], a[r]);
        if(cur > dp[l][r]){
            dp[l][r] = cur;
            el = i;
        }
    }

    return dp[l][r];
}

//void show(int l, int r){
//    if(r - l == 0){
//        return;
//    }
//
//    int pos = -1;
//    for(int i = l + 1; i < r; i++){
//        if(dp[l][r] == get(l, i) + get(i, r) + min(a[l], a[r])){
//            pos = i;
//            break;
//        }
//    }
//
//    if(pos != -1){
//        cout << l << " " << pos << " " << pos << " " << r << "\n";
//        show(l, pos);
//        show(pos, r);
//    }
//}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    ll ans = 0;
    stack<int> s;
    for(int i = 0; i < n; i++){
        while(s.size() >= 2){
            int top = s.top();
            s.pop();

            if(s.top() < top || top > a[i]){
                s.push(top);
                break;
            }

            ans += min(s.top(), a[i]);
        }
        s.push(a[i]);
    }

    int *end = &s.top() + 1;
    int *begin = end - s.size();
    vector<int> b(begin, end);

    int cur = 0;
    int l = 0;
    int r = int(b.size()) - 1;
    while(l < r - 1){
        ans += (min(b[l], b[r]) - cur + 0ll) * (r - l - 1);
        cur = min(b[l], b[r]);
        if(b[l] <= b[r]){
            ++l;
        } else {
            --r;
        }
    }

    cout << ans << "\n";
}

/*
10
96 66 8 18 30 48 34 11 37 42

4
96 66 48 42
*/


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return a[l] + a[r];
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    int el = -1;
    for(int i = l + 1; i < r; i++){
        int cur = get(l, i) + get(i, r) + min(a[l], a[r]);
        if(cur > dp[l][r]){
            dp[l][r] = cur;
            el = i;
        }
    }

    return dp[l][r];
}

//void show(int l, int r){
//    if(r - l == 0){
//        return;
//    }
//
//    int pos = -1;
//    for(int i = l + 1; i < r; i++){
//        if(dp[l][r] == get(l, i) + get(i, r) + min(a[l], a[r])){
//            pos = i;
//            break;
//        }
//    }
//
//    if(pos != -1){
//        cout << l << " " << pos << " " << pos << " " << r << "\n";
//        show(l, pos);
//        show(pos, r);
//    }
//}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    int sum = 0, sum2 = 0;
    for(int i = 0; i < n; i++){
        cin >> a[i];
        sum += a[i];
        if(i > 0 && i < n - 1){
            sum2 += a[i];
        }
    }
    if(n < 3){
        return cout << 0, 0;
    }

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            dp[i][j] = -inf;
        }
    }

    cout << get(0, n - 1) - sum - sum2 << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
const int M = 1e3 + 5;
const int inf = 2000000000;

int dp[M][M];
int n, a[N];

int get(int l, int r){
    if(r - l == 1){
        return 0;
    }
    if(dp[l][r] > 0){
        return dp[l][r];
    }

    for(int i = l + 1; i < r; i++){
        dp[l][r] = max(dp[l][r], get(l, i) + get(i, r) + min(a[l], a[r]));
    }

    return dp[l][r];
}

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    if(n < 3){
        return cout << 0, 0;
    }

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            dp[i][j] = -inf;
        }
    }

    cout << get(0, n - 1) << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int inf = 2000000000;
const int N = 1e5 + 5;

int n, a[N];

int checkOrder(vector<int>& b){
    set<int> s;
    for(int i = 0; i < n; i++){
        s.insert(i);
    }
    int ans = 0;
    for(auto val : b){
        auto it = s.upper_bound(val);
        int next = *it;
        int prev = *(----it);
        ans += min(a[next], a[prev]);
        s.erase(val);
    }
    return ans;
}
int solveStupid(){
    vector<int> b;
    for(int i = 1; i < n - 1; i++){
        b.pb(i);
    }

    int ans = checkOrder(b);
    while(next_permutation(b.begin(), b.end())){
        ans = max(ans, checkOrder(b));
    }
    return ans;
}

int getNext(int pos, bool use[]){
    for(int i = pos + 1; i < n; i++){
        if(!use[i]){
            return a[i];
        }
    }
}
int getPrev(int pos, bool use[]){
    for(int i = pos - 1; i >= 0; i--){
        if(!use[i]){
            return a[i];
        }
    }
}
int f(int pos, bool use[]){
    return min(getNext(pos, use), getPrev(pos, use));
}
int solveGreed(){
    bool use[n];
    memset(use, false, sizeof(use));

    int ans = 0;
    for(int i = 0; i < n - 2; i++){
        int cur = -1, pos = -1;
        for(int j = 1; j < n - 1; j++){
            if(!use[j]){
                int tmp = f(j, use);
                if(tmp > cur){
                    cur = tmp;
                    pos = j;
                }
            }
        }

        use[pos] = true;
        ans += cur;
    }
    return ans;
}

main(){
    srand(time(NULL));
    cin.tie(0);
    ios_base::sync_with_stdio(0);

//    cin >> n;
//    n = rand() % 10 + 2;
//    cout << n << "\n";
//    for(int i = 0; i < n; i++){
//        cin >> a[i];
//        a[i] = rand() % 1000;
//        cout << a[i] << " ";
//    }
//    cout << "\n";

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    cout << solveGreed() << "\n";
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double K;
typedef pair<int, int> pii;

#define x first
#define y second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(), (a).end()

const int N = 5e5 + 5;
int n, a[N];

main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);

    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }

    ll ans = 0;
    stack<int> s;
    for(int i = 0; i < n; i++){
        while(s.size() >= 2){
            int top = s.top();
            s.pop();

            if(s.top() < top || top > a[i]){
                s.push(top);
                break;
            }

            ans += min(s.top(), a[i]);
        }
        s.push(a[i]);
    }

    int *end = &s.top() + 1;
    int *begin = end - s.size();
    vector<int> b(begin, end);
    for(int i = 1; i < b.size() - 1; i++){
        ans += min(b[i - 1], b[i + 1]);
    }
    cout << ans << "\n";
}


#include <bits/stdc++.h>
using namespace std;

vector<string> vec_splitter(string s) {
	s += ',';
	vector<string> res;
	while(!s.empty()) {
		res.push_back(s.substr(0, s.find(',')));
		s = s.substr(s.find(',') + 1);
	}
	return res;
}
void debug_out(vector<string> __attribute__ ((unused)) args,__attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
	if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
	stringstream ss; ss << H;
	cerr << args[idx] << " = " << ss.str();
	debug_out(args, idx + 1, LINE_NUM, T...);
}
#ifdef XOX
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
#else
#define debug(...) 42
#endif

#define ll long long
#define pll pair<ll,ll>
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
#define abs(x) ((x)<0?(-(x)):(x))
#define SZ(x) ((int)x.size())
#define all(x) x.begin(),x.end()

const int LOG = 21;
const int NN = (int)5e5+5;
const int MAXN = (int)60000+5;
const int MOD = (int)1e9+7;
const int INF = 1 << 27;

int mul(int x, int y) { return (1LL * x * y) % MOD; }
int add(int x, int y) {
	ll res = x;
	res += y;
	return (res % MOD + MOD) % MOD;
}
int fast_pow(int x, int y) {
	if(y == 0) return 1;
	if(y & 1) return mul(x, fast_pow(x, y - 1));
	else {
		int aux = fast_pow(x, y >> 1);
		return mul(aux, aux);
	}
}
int two(int x) { return 1 << x; }
bool contain(int mask, int bit) { return (mask & two(bit)) > 0; }
int gcd(int a, int b) { return b == 0? a: gcd(b, a % b); }
ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); }
int bit_count(int x) { return x == 0? 0: (x & 1) + bit_count(x >> 1); }

int n;
int a[NN];

int main() {
	#ifdef XOX
		freopen("in.txt", "r", stdin);
	#endif

	scanf("%d", &n);
	for(int i = 0; i < n; i ++) scanf("%d", &a[i]);

	int f = 0, b = n - 1;
	ll ans = 0;
	while(b - f + 1 >= 3) {
		if(a[f] < a[b]) {
			int aux = f, cnt = 0;
			while(b - aux + 1 >= 3 && a[aux] <= a[f]) cnt ++, aux ++;
			ans += 1LL * cnt * a[f];
			f = aux;
		} else {
			int aux = b, cnt = 0;
			while(aux - f + 1 >= 3 && a[aux] <= a[b]) cnt ++, aux --;
			ans += 1LL * cnt * a[b];
			b = aux;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

vector<string> vec_splitter(string s) {
	s += ',';
	vector<string> res;
	while(!s.empty()) {
		res.push_back(s.substr(0, s.find(',')));
		s = s.substr(s.find(',') + 1);
	}
	return res;
}
void debug_out(vector<string> __attribute__ ((unused)) args,__attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
	if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
	stringstream ss; ss << H;
	cerr << args[idx] << " = " << ss.str();
	debug_out(args, idx + 1, LINE_NUM, T...);
}
#ifdef XOX
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
#else
#define debug(...) 42
#endif

#define ll long long
#define pll pair<ll,ll>
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
#define abs(x) ((x)<0?(-(x)):(x))
#define SZ(x) ((int)x.size())
#define all(x) x.begin(),x.end()

const int LOG = 21;
const int NN = (int)5e5+5;
const int MAXN = (int)60000+5;
const int MOD = (int)1e9+7;
const int INF = 1 << 27;

int mul(int x, int y) { return (1LL * x * y) % MOD; }
int add(int x, int y) {
	ll res = x;
	res += y;
	return (res % MOD + MOD) % MOD;
}
int fast_pow(int x, int y) {
	if(y == 0) return 1;
	if(y & 1) return mul(x, fast_pow(x, y - 1));
	else {
		int aux = fast_pow(x, y >> 1);
		return mul(aux, aux);
	}
}
int two(int x) { return 1 << x; }
bool contain(int mask, int bit) { return (mask & two(bit)) > 0; }
int gcd(int a, int b) { return b == 0? a: gcd(b, a % b); }
ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); }
int bit_count(int x) { return x == 0? 0: (x & 1) + bit_count(x >> 1); }

int n;
int a[NN], nxt[NN], pre[NN];
pair<int,int> s[NN];

int main() {
	#ifdef XOX
		freopen("in.txt", "r", stdin);
	#endif

	scanf("%d", &n);
	for(int i = 0; i < n; i ++) scanf("%d", &a[i]), s[i] = {a[i], i};

	for(int i = 0; i < n; i ++) {
		nxt[i] = i + 1;
		pre[i] = i - 1;
	}
	sort(s, s + n);
	ll ans = 0;
	for(int i = 0; i < n - 2; i ++) {
		int idx = s[i].second;
		if(pre[idx] == -1 || nxt[idx] == n) {
			ans += s[i].first;
		} else {
			ans += min(a[pre[idx]], a[nxt[idx]]);
		}
		if(pre[idx] != -1) {
			nxt[pre[idx]] = nxt[idx];
		}
		if(nxt[idx] != n) {
			pre[nxt[idx]] = pre[idx];
		}
	}

	printf("%lld\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n, l[N], r[N], a[N];
vector<int> fr, sd;
set<pair<int, int> > s;
long long ans;
int main() {
	ios_base::sync_with_stdio (false), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i], l[i] = i - 1, r[i] = i + 1;
	for (int i = 1; i < n - 1; i++)
		s.insert({a[i], i});
	fr.push_back(0), sd.push_back(n - 1);
	while (!s.empty()) {
		auto p = *(s.begin());
		s.erase(s.begin());
		int plc = p.second, val = p.first;
		if (l[plc] == fr.back() && val > a[fr.back()]) {
			fr.push_back(plc);
			continue;
		}
		if (r[plc] == sd.back() && val > a[sd.back()]) {
			sd.push_back(plc);
			continue;
		}
		ans += min(a[l[plc]], a[r[plc]]);
		l[r[plc]] = l[plc];
		r[l[plc]] = r[plc];
	}
//	cout << ans << endl;
	if (a[fr.back()] < a[sd.back()])
		swap(fr, sd);
	if (fr.size() > 1) {
		if (a[fr[fr.size() - 2]] > a[sd.back()])
			sd.push_back(fr.back()), fr.pop_back();
	}
//	for (auto u : fr)
//		cout << u << " ";
//	cout << endl;
//	for (auto u : sd)
//		cout << u << " ";
//	cout << endl;
	while (fr.size() > 1 || sd.size() > 1) {
		if (fr.size() == 1) {
			ans += min(a[fr.back()], a[sd[sd.size() - 2]]);
			sd.pop_back();
			continue;
		}
		if (sd.size() == 1) {
			ans += min(a[sd.back()], a[fr[fr.size() - 2]]);
			fr.pop_back();
			continue;
		}
		if (a[fr[fr.size() - 2]] > a[sd[sd.size() - 2]]) {
			ans += min(a[sd.back()], a[fr[fr.size() - 2]]);
			fr.pop_back();
		}
		else {
			ans += min(a[fr.back()], a[sd[sd.size() - 2]]);
			sd.pop_back();
		}
	}
	cout << ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n, l[N], r[N], a[N];
vector<int> fr, sd;
set<pair<int, int> > s;
long long ans;
int main() {
	ios_base::sync_with_stdio (false), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i], l[i] = i - 1, r[i] = i + 1;
	for (int i = 1; i < n - 1; i++)
		s.insert({a[i], i});
	fr.push_back(0), sd.push_back(n - 1);
	while (!s.empty()) {
		auto p = *(s.begin());
		s.erase(s.begin());
		int plc = p.second, val = p.first;
		if (l[plc] == fr.back() && val > a[fr.back()]) {
			fr.push_back(plc);
			continue;
		}
		if (r[plc] == sd.back() && val > a[sd.back()]) {
			sd.push_back(plc);
			continue;
		}
		ans += min(a[l[plc]], a[r[plc]]);
		l[r[plc]] = l[plc];
		r[l[plc]] = r[plc];
	}
	while (fr.size() > 1 || sd.size() > 1) {
		if (fr.size() == 1) {
			ans += min(a[fr.back()], a[sd[sd.size() - 2]]);
			sd.pop_back();
			continue;
		}
		if (sd.size() == 1) {
			ans += min(a[sd.back()], a[fr[fr.size() - 2]]);
			fr.pop_back();
			continue;
		}
		if (a[fr[fr.size() - 2]] > a[sd[sd.size() - 2]]) {
			ans += min(a[sd.back()], a[fr[fr.size() - 2]]);
			fr.pop_back();
		}
		else {
			ans += min(a[fr.back()], a[sd[sd.size() - 2]]);
			sd.pop_back();
		}
	}
	cout << ans;
	return 0;
}


#include <cstdio>
#include <algorithm>
#include <vector>
#define file(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)

inline int read()
{
	int data = 0, w = 1; char ch = getchar();
	while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
	if (ch == '-') w = -1, ch = getchar();
	while (ch >= '0' && ch <= '9') data = data * 10 + (ch ^ 48), ch = getchar();
	return data * w;
}

const int N(5e5 + 10);
int n, a[N], stk[N], top;
long long ans;

int main()
{
	n = read();
	for (int i = 1; i <= n; i++) a[i] = read();
	for (int i = 1; i <= n; i++)
	{
		while (top > 1 && stk[top - 1] >= stk[top] && stk[top] <= a[i])
			ans += std::min(a[i], stk[top - 1]), --top;
		stk[++top] = a[i];
	}
	std::sort(stk + 1, stk + top + 1);
	for (int i = 1; i <= top - 2; i++) ans += stk[i];
	printf("%lld\n", ans);
	return 0;
}
//


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
using namespace std;

const int N=5e5+5;
int n,pre[N],nxt[N],a[N];
pair<int,int> p[N];

int main() {
	#ifdef kvutxdy
	freopen("C:/Users/khanh/OneDrive/RoadtoPurple/Code/Codeforces/input.in", "r", stdin);
	#endif
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cin>>n;
	for(int i=0;i<n;++i){
		cin>>a[i];
		pre[i]=i-1;
		nxt[i]=i+1;
		p[i]={a[i],i};
	}
	sort(p,p+n);
	ll res=0LL;
	for(int i=0;i<n-2;++i){
		int pos=p[i].se;
		if(pre[pos]!=-1&&nxt[pos]!=n) res+=min(a[pre[pos]],a[nxt[pos]]);
		else res+=a[pos];
		nxt[pre[pos]]=nxt[pos];
		pre[nxt[pos]]=pre[pos];
	}
	cout<<res;
}


#include<bits/stdc++.h>
using namespace std;

#define int long long
#define fs first
#define sc second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define sz(x) (int)x.size()
#define pb push_back
#define fastio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define MP make_pair
#define sqr(x) ((x) * (x))
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

signed main() {
    fastio;
#ifdef FlameDragon
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    int n;
    cin >> n;
    if (n <= 2) {
        cout << "0\n";
        return 0;
    }
    vector<int> a(n);
    vector<pair<int, int>> order;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        order.pb(MP(a[i], i));
    }
    sort(all(order));
    order.pop_back();
    order.pop_back();
    set<int> alive;
    for (int i = 0; i < n; i++) {
        alive.insert(i);
    }

    int ans = 0;
    int delta = 0;
    for (auto i : order) {
        int pos = i.sc;
        auto it = alive.lower_bound(pos);
        if (it == alive.begin() || next(it) == alive.end()) {
            ans += (sz(alive) - 2) * (i.fs - delta);
            delta = i.fs;
            alive.erase(pos);
            continue;
        }
        it--;
        int add = a[*it];
        it++;
        it++;
        add = min(add, a[*it]);
        add -= delta;
        it--;
        alive.erase(it);
        ans += add;
    }
    cout << ans << '\n';
}


#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 100;

int a[N];

int main() {
    // freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;
    set<int> gorto;
    for(int i = 1; i <= n; i++) cin >> a[i];
    if(n <= 2) {
        cout << "0" << endl;
        exit(0);
    }
    for(int i = 2; i < n; i++) {
        if(a[i] <= a[i-1] && a[i] <= a[i+1]) gorto.insert(i);
    }
    set<int> alive;
    for(int i = 1; i <= n; i++) {
        alive.insert(i);
    }
    long long ans = 0;
    while(gorto.size() > 0) {
        int idx = *gorto.begin();
        gorto.erase(idx);
        auto it = alive.upper_bound(idx);
        int nxt = *it;
        it--;
        it--;
        int prev = *it;
        ans += min(a[nxt], a[prev]);
        alive.erase(idx);
    }
    set<pair<int,int>> pahar;
    for(int x : alive) {
        if(x == 1 or x == n) continue;
        pahar.insert({a[x], x});
    }
    while(pahar.size() > 0) {
        int idx = (*pahar.rbegin()).second;
        pahar.erase({a[idx],idx});
        auto it = alive.upper_bound(idx);
        int nxt = *it;
        it--;
        it--;
        int prev = *it;
        ans += min(a[nxt], a[prev]);
        alive.erase(idx);
    }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 100;

int a[N];

int main() {
    // freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;
    set<int> gorto;
    for(int i = 1; i <= n; i++) cin >> a[i];
    if(n <= 2) {
        cout << "0" << endl;
        exit(0);
    }
    for(int i = 2; i < n; i++) {
        if(a[i] <= a[i-1] && a[i] <= a[i+1]) gorto.insert(i);
    }
    set<int> alive;
    for(int i = 1; i <= n; i++) {
        alive.insert(i);
    }
    long long ans = 0;
    while(gorto.size() > 0) {
        int idx = *gorto.begin();
        gorto.erase(idx);
        auto it = alive.upper_bound(idx);
        int nxt = *it;
        it--;
        it--;
        int prev = *it;
        ans += min(a[nxt], a[prev]);
        alive.erase(idx);

        if(gorto.find(nxt) != gorto.end()) gorto.erase(nxt);
        if(gorto.find(prev) != gorto.end()) gorto.erase(prev);

        if(nxt != n) {
            it = alive.upper_bound(nxt);
            int x = a[*it];
            it--;
            it--;
            int y = a[*it];
            if(min(x, y) >= a[nxt]) gorto.insert(nxt);
        }

        if(prev != 1) {
            it = alive.upper_bound(prev);
            int x = a[*it];
            it--;
            it--;
            int y = a[*it];
            if(min(x, y) >= a[prev]) gorto.insert(prev);
        }
    }
    vector<int> baki;
    for(int x : alive) {
        baki.push_back(a[x]);
    }
    sort(baki.begin(), baki.end());
    for(int i = 0; i+2 < baki.size(); i++) {
        ans += baki[i];
    }
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> a(n), prv(n, -1), nxt(n, -1);
  for (int i = 0; i < n; ++i) cin >> a[i];
  for (int i = 0; i < n; ++i) {
    if (i > 0) prv[i] = i - 1;
    if (i + 1 < n) nxt[i] = i + 1;
  }

  vector<int> ord(n);
  iota(ord.begin(), ord.end(), 0);
  sort(ord.begin(), ord.end(), [&](int i, int j) { return a[i] < a[j]; });

  int64_t res = 0;
  for (int i = 0; i < n - 2; ++i) {
    if (nxt[ord[i]] == -1) {
      res += a[ord[i]];
      nxt[prv[ord[i]]] = -1;
    } else if (prv[ord[i]] == -1) {
      res += a[ord[i]];
      prv[nxt[ord[i]]] = -1;
    } else {
      res += min(a[prv[ord[i]]], a[nxt[ord[i]]]);
      nxt[prv[ord[i]]] = nxt[ord[i]];
      prv[nxt[ord[i]]] = prv[ord[i]];
    }
  }
  cout << res << "\n";
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> a(n), prv(n, -1), nxt(n, -1);
  for (int i = 0; i < n; ++i) cin >> a[i];
  set<pair<int, int>> st;
  for (int i = 0; i < n; ++i) {
    if (i > 0) prv[i] = i - 1;
    if (i + 1 < n) nxt[i] = i + 1;
    if (i > 0 && i + 1 < n) {
      st.insert(make_pair(min(a[i - 1], a[i + 1]), i));
    }
  }
  int64_t res = 0;

  auto Remove = [&](int p) {
    if (prv[p] != -1 && nxt[p] != -1) {
      st.erase(make_pair(min(a[prv[p]], a[nxt[p]]), p));
    }
  };

  auto Insert = [&](int p) {
    if (prv[p] != -1 && nxt[p] != -1) {
      st.insert(make_pair(min(a[prv[p]], a[nxt[p]]), p));
    }
  };

  for (int it = 0; it < n - 2; ++it) {
    auto p = *st.rbegin();
    st.erase(p);
    res += p.first;
    Remove(prv[p.second]);
    Remove(nxt[p.second]);
    nxt[prv[p.second]] = nxt[p.second];
    prv[nxt[p.second]] = prv[p.second];
    Insert(prv[p.second]);
    Insert(nxt[p.second]);
  }
  cout << res << "\n";
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long ul;
#define all(x) (x).begin(), (x).end()
#define pi 3.1415926536

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x): val(x), left(NULL), right(NULL){}
};

struct ListNode {
    int val;
    ListNode* next;

    ListNode(int x): val(x), next(NULL){}
};

int nxt(){
    int x;
    cin>>x;
    return x;
}

ll nxtLong(){
    ll x;
    cin>>x;
    return x;
}

string nxtStr(){
    string x;
    cin>>x;
    return x;
}

char nxtChar(){
    char x;
    cin>>x;
    return x;
}

double nxtDouble(){
    double x;
    cin>>x;
    return x;
}

ld nxtLDouble(){
    ld x;
    cin>>x;
    return x;
}

TreeNode* makeTree(int n){
    queue<TreeNode*> tree_nodes;
    TreeNode* root;
    if(n){
        root = new TreeNode(nxt());
        tree_nodes.push(root);
    }else{
        return NULL;
    }
    while(!tree_nodes.empty()){
        TreeNode* node = tree_nodes.front();
        tree_nodes.pop();
        bool left;
        cin>>left;
        if(left){
            node->left = new TreeNode(nxt());
            tree_nodes.push(node->left);
        }
        bool right;
        cin>>right;
        if(right){
            node->right = new TreeNode(nxt());
            tree_nodes.push(node->right);
        }
    }
    return root;
}

ListNode* makeLinkedList(int n){
    ListNode* list = new ListNode(0);
    ListNode* dummy = list;

    for(int i=0;i<n;++i){
        list->next = new ListNode(nxt());
        list = list->next;
    }

    return dummy->next;
}

void solve(){
    int n = nxt();
    vector<ll> in(n);
    ll ans = 0;
    int x = -1;
    while(n--){
        x++;
        cin>>in[x];
        while(x>=2 && in[x-1] <= min(in[x-2], in[x])){
            ans += min(in[x-2], in[x]);
            in[x-1] = in[x];
            x--;
        }
    }

    for(int i=1;i<x;++i){
        ans += min(in[i-1], in[i+1]);
    }

    cout<<ans<<endl;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout<<fixed<<setprecision(9);
    //ll t;
    //cin>>t;
    //while(t--){
    //    solve();
    //}
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long ul;
#define all(x) (x).begin(), (x).end()
#define pi 3.1415926536

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x): val(x), left(NULL), right(NULL){}
};

struct ListNode {
    int val;
    ListNode* next;

    ListNode(int x): val(x), next(NULL){}
};

int nxt(){
    int x;
    cin>>x;
    return x;
}

ll nxtLong(){
    ll x;
    cin>>x;
    return x;
}

string nxtStr(){
    string x;
    cin>>x;
    return x;
}

char nxtChar(){
    char x;
    cin>>x;
    return x;
}

double nxtDouble(){
    double x;
    cin>>x;
    return x;
}

ld nxtLDouble(){
    ld x;
    cin>>x;
    return x;
}

TreeNode* makeTree(int n){
    queue<TreeNode*> tree_nodes;
    TreeNode* root;
    if(n){
        root = new TreeNode(nxt());
        tree_nodes.push(root);
    }else{
        return NULL;
    }
    while(!tree_nodes.empty()){
        TreeNode* node = tree_nodes.front();
        tree_nodes.pop();
        bool left;
        cin>>left;
        if(left){
            node->left = new TreeNode(nxt());
            tree_nodes.push(node->left);
        }
        bool right;
        cin>>right;
        if(right){
            node->right = new TreeNode(nxt());
            tree_nodes.push(node->right);
        }
    }
    return root;
}

ListNode* makeLinkedList(int n){
    ListNode* list = new ListNode(0);
    ListNode* dummy = list;

    for(int i=0;i<n;++i){
        list->next = new ListNode(nxt());
        list = list->next;
    }

    return dummy->next;
}

void solve(){
    int n = nxt();
    vector<int> in(n);
    int ans = 0;
    int x = -1;
    while(n--){
        x++;
        cin>>in[x];
        while(x>=2 && in[x-1] <= min(in[x-2], in[x])){
            ans += min(in[x-2], in[x]);
            in[x-1] = in[x];
            x--;
        }
    }

    for(int i=1;i<x;++i){
        ans += min(in[i-1], in[i+1]);
    }

    cout<<ans<<endl;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout<<fixed<<setprecision(9);
    //ll t;
    //cin>>t;
    //while(t--){
    //    solve();
    //}
    solve();
    return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;
const int N=100000+10;
typedef long long LL;
int n,a[N]; LL ans;
int stk[N],top;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    stk[++top]=1,stk[++top]=2;
    for(int i=3;i<=n;i++){
        while(top>=2 && a[stk[top]]<=a[stk[top-1]] && a[stk[top]]<=a[i]) {
            ans += min(a[stk[top-1]],a[i]); top--;
        }
        stk[++top]=i;
    }
    for(int i=1;i<=top;i++)stk[i]=a[stk[i]];
    sort(stk+1,stk+1+top);
    for(int i=1;i<=top-2;i++)ans+=stk[i];
    cout<<ans<<endl;
}


#include <iostream>
#include <algorithm>
using namespace std;
const int N=500000+10;
typedef long long LL;
int n,a[N]; LL ans;
int stk[N],top;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    stk[++top]=1,stk[++top]=2;
    for(int i=3;i<=n;i++){
        while(top>=2 && a[stk[top]]<=a[stk[top-1]] && a[stk[top]]<=a[i]) {
            ans += min(a[stk[top-1]],a[i]); top--;
        }
        stk[++top]=i;
    }
    for(int i=1;i<=top;i++)stk[i]=a[stk[i]];
    sort(stk+1,stk+1+top);
    for(int i=1;i<=top-2;i++)ans+=stk[i];
    cout<<ans<<endl;
}