/* ID: usaco.t3 TASK: test LANG: C++14 */ #pragma GCC optimize ("O3") /****Author: Barish Namazov****/ #include using namespace std; /***TEMPLATE***/ #define intt long long #define pii pair #define vi vector #define vii vector #define all(v) (v).begin(),(v).end() #define rall(v) (v).rbegin(),(v).rend() #define F first #define S second #define pb push_back #define IO ios_base::sync_with_stdio(false);cin.tie(); #define endl '\n' #define wtfis(x) cerr << "at line " << __LINE__ << ": " << #x << " = " << (x) << endl const intt max3 = 1003; const intt max4 = 10004; const intt maxx = 100005; const intt max6 = 1000006; const intt max7 = 10000007; const intt lg4 = 13; const intt lg5 = 17; const intt lg6 = 20; const intt INF = 2LL * 1000000000; const intt INFLL = 9LL * 1000000000 * 1000000000; /***************/ intt powmod (intt a, intt b, intt mod) { intt res = 1; a %= mod; for (; b; b >>= 1) { if (b & 1) res = (res * a) % mod; a = (a * a) % mod; } return res; } intt gcd (intt a, intt b) { while (b > 0) { intt t = a % b; a = b, b = t; } return a; } intt lcm (intt a, intt b) { return (a / gcd (a, b)) * b; } intt is_prime (intt n) { if (n <= 1 || n > 3 && (n % 2 == 0 || n % 3 == 0)) return 0; for (intt i = 5, t = 2; i * i <= n; i += t, t = 6 - t) if (n % i == 0) return 0; return 1; } /**************************/ intt dp[5000][5000]; vector solve (vector A) { intt n = A.size(); for (intt i = 0; i < n; i++){ dp[i][i] = A[i]; for (intt j = i + 1; j < n; j++) { dp[i][j] = max (A[j], dp[i][j - 1]); } } vector B; for (intt i = 0; i < n; i++) { for (intt j = 0; j < n - i; j++) { intt k = i + j; B.pb (dp[j][k]); } } return B; } int main() { intt n; cin >> n; vector A(n); for (intt i = 0; i < n; i++) { cin >> A[i]; } vi res = solve (solve (A)); intt sum = 0; for (intt i = 0; i < res.size(); i++) { sum += res[i]; } cout << sum << endl; return 0; }