#include <bits/stdc++.h>
// iostream is too mainstream
#include <cstdio>
// bitch please
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <cmath>
#include <iomanip>
#include <time.h>
#define dibs reserve
#define OVER9000 1234567890
#define ALL_THE(CAKE,LIE) for(auto LIE =CAKE.begin(); LIE != CAKE.end(); LIE++)
#define tisic 47
#define soclose 1e-8
#define chocolate win
// so much chocolate
#define patkan 9
#define ff first
#define ss second
#define abs(x) ((x < 0)?-(x):x)
#define uint unsigned int
#define dbl long double
#define pi 3.14159265358979323846
using namespace std;
// mylittledoge
#ifdef DONLINE_JUDGE
// palindromic tree is better than splay tree!
#define lld I64d
#endif
int ans[51][51][50][50];
int N;
vector<int> A;
void solve(int z, int k, int l, int r) {
if(ans[z][k][l][r] >= 0) return;
if(z >= k) {
ans[z][k][l][r] =0;
return;}
solve(z+1,k,l,r);
solve(z,k-1,l,r);
ans[z][k][l][r] =max(ans[z+1][k][l][r],ans[z][k-1][l][r]);
if(A[z] >= l && A[z] <= r) {
solve(z+1,k,A[z],r);
ans[z][k][l][r] =max(ans[z][k][l][r],ans[z+1][k][A[z]][r]+1);}
if(A[k-1] >= l && A[k-1] <= r) {
solve(z,k-1,l,A[k-1]);
ans[z][k][l][r] =max(ans[z][k][l][r],ans[z][k-1][l][A[k-1]]+1);}
if(z < k-1 && l <= A[k-1] && A[k-1] <= A[z] && A[z] <= r) {
solve(z+1,k-1,A[k-1],A[z]);
ans[z][k][l][r] =max(ans[z][k][l][r],ans[z+1][k-1][A[k-1]][A[z]]+2);}
if(z < k-1 && l <= A[k-1] && A[k-1] <= r) {
solve(z+1,k-1,A[k-1],r);
ans[z][k][l][r] =max(ans[z][k][l][r],ans[z+1][k-1][A[k-1]][r]+1);}
if(z < k-1 && l <= A[z] && A[z] <= r) {
solve(z+1,k-1,l,A[z]);
ans[z][k][l][r] =max(ans[z][k][l][r],ans[z+1][k-1][l][A[z]]+1);}
}
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(10);
#ifndef LOCAL
freopen("subrev.in","r",stdin);
freopen("subrev.out","w",stdout);
#endif
memset(ans,-10,sizeof(ans));
cin >> N;
A.resize(N);
for(int i =0; i < N; i++) {
cin >> A[i];
A[i]--;}
solve(0,N,0,49);
cout << ans[0][N][0][49] << "\n";
return 0;}
// look at my code
// my code is amazing
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+Ci8vIGlvc3RyZWFtIGlzIHRvbyBtYWluc3RyZWFtCiNpbmNsdWRlIDxjc3RkaW8+Ci8vIGJpdGNoIHBsZWFzZQojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxhbGdvcml0aG0+CiNpbmNsdWRlIDxjc3RkbGliPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8c2V0PgojaW5jbHVkZSA8bWFwPgojaW5jbHVkZSA8cXVldWU+CiNpbmNsdWRlIDxzdGFjaz4KI2luY2x1ZGUgPGxpc3Q+CiNpbmNsdWRlIDxjbWF0aD4KI2luY2x1ZGUgPGlvbWFuaXA+CiNpbmNsdWRlIDx0aW1lLmg+CiNkZWZpbmUgZGlicyByZXNlcnZlCiNkZWZpbmUgT1ZFUjkwMDAgMTIzNDU2Nzg5MAojZGVmaW5lIEFMTF9USEUoQ0FLRSxMSUUpIGZvcihhdXRvIExJRSA9Q0FLRS5iZWdpbigpOyBMSUUgIT0gQ0FLRS5lbmQoKTsgTElFKyspCiNkZWZpbmUgdGlzaWMgNDcKI2RlZmluZSBzb2Nsb3NlIDFlLTgKI2RlZmluZSBjaG9jb2xhdGUgd2luCi8vIHNvIG11Y2ggY2hvY29sYXRlCiNkZWZpbmUgcGF0a2FuIDkKI2RlZmluZSBmZiBmaXJzdAojZGVmaW5lIHNzIHNlY29uZAojZGVmaW5lIGFicyh4KSAoKHggPCAwKT8tKHgpOngpCiNkZWZpbmUgdWludCB1bnNpZ25lZCBpbnQKI2RlZm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