#include <iostream>
#include <iomanip>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <bitset>
#include <set>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define RREP(i,n) for(int i=n-1;i>=0;i--)
#define FOR(i,k,n) for(int i=(k);i<(int)(n);i++)
#define all(i,n) (i),(i+n)

int dx4[4]={1,0,-1,0};
int dy4[4]={0,-1,0,1};
int dx8[8]={1,0,-1,1,-1,1,0,-1};
int dy8[8]={1,1,1,0,0,-1,-1,-1};
int dx9[9]={0,1,0,-1,1,-1,1,0,-1};
int dy9[9]={0,1,1,1,0,0,-1,-1,-1};

typedef pair<int, int> P;
typedef pair<string, int> SP;
typedef long long ll;
typedef pair<ll, ll> PLL;

const int INF = 1e9;
const ll LLINF = 1e18;
const int MAX_V = 1e6+1;
const ll mod = 1000000007;
// << fixed << setprecision
// --------------------------------------
int n;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin >> n;

  ll ans = 1;
  int c[3];
  REP(i, 3) c[i] = 0;
  REP(i, n) {
    int a;
    cin >> a;
    int t = 0, p = 0;
    REP(j, 3) if(c[j] == a) {
      t++; p = j;
    }

    ans = (ans * t) % mod;
    c[p]++;
  }

  cout << ans << endl;
}

#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <deque>
#include <array>
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define range(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
#define all(x) x.begin(), x.end()
#define PI 3.1415926536

using namespace std;

const int MAX_N = 5000;
array<int, MAX_N + 1> bit;
int sets, n;

int sum(int i){
  int ret = 0;
  while(i > 0){
    ret += bit[i];
    i -= i & -i;
  }
  return ret;
}

void add(int i, int x){
  while(i <= n){
    bit[i] += x;
    i += i & -i;
  }
}

void solve(){
  cin >> n;
  if(n == 0) exit(0);
  bit.fill(0);
  for (int i = 1; i <= n; ++i) {
    int t; cin >> t;
    add(i, t);
  }

  int ans = -1e9;
  for (int i = 0; i <= n; ++i) {
    for (int j = i + 1; j <= n; ++j) {
      ans = max(ans, sum(j) - sum(i));
    }
  }
  cout << ans << endl;
}

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

  for(;;) solve();

  return 0;
}