#include <bits/stdc++.h>
using namespace std;
template <class X, class Y>
void minimize(X &x, const Y &y) {
  if (x > y) x = y;
}
template <class X, class Y>
void maximize(X &x, const Y &y) {
  if (x < y) x = y;
}
template <class T>
T Abs(const T &x) {
  return (x < 0 ? -x : x);
}
int a[1024], ___next[1024][8 + 3][1024], nextPos[1024][8 + 3], n;
int f[(1LL << (2 * (8))) + 3];
bool valid[(1LL << (2 * (8))) + 3];
void init(void) {
  scanf("%d", &n);
  for (int i = (1), _b = (n); i <= _b; i = i + 1) scanf("%d", &a[i]);
  for (int i = (1), _b = (n); i <= _b; i = i + 1) a[i]--;
}
void prepare(void) {
  for (int i = 0, _n = (8); i < _n; i = i + 1) nextPos[n][i] = n + 1;
  for (int i = (n - 1), _a = (0); i >= _a; i = i - 1) {
    for (int j = 0, _n = (8); j < _n; j = j + 1)
      nextPos[i][j] = nextPos[i + 1][j];
    nextPos[i][a[i + 1]] = i + 1;
  }
  for (int j = 0, _n = (8); j < _n; j = j + 1)
    for (int k = 0, _n = (1024); k < _n; k = k + 1) ___next[n][j][k] = n + 1;
  for (int i = (n - 1), _a = (0); i >= _a; i = i - 1)
    for (int j = 0, _n = (8); j < _n; j = j + 1) {
      ___next[i][j][1] = nextPos[i][j];
      for (int k = (2), _b = (1024 - 1); k <= _b; k = k + 1)
        ___next[i][j][k] =
            nextPos[i][j] <= n ? ___next[nextPos[i][j]][j][k - 1] : n + 1;
    }
  for (int i = 0, _n = ((1LL << (2 * (8)))); i < _n; i = i + 1) {
    valid[i] = true;
    for (int j = 0, _n = (8); j < _n; j = j + 1)
      if ((((i) >> (2 * (j))) & 3) == 3) valid[i] = false;
  }
}
int maxSeq(int length) {
  memset(f, 0x3f, sizeof f);
  int res = -1;
  f[0] = 0;
  for (int i = 0, _n = ((1LL << (2 * (8)))); i < _n; i = i + 1)
    if (valid[i] && f[i] <= n) {
      bool done = true;
      int value = 0;
      for (int j = 0, _n = (8); j < _n; j = j + 1) {
        if ((((i) >> (2 * (j))) & 3) == 2) value++;
        if ((((i) >> (2 * (j))) & 3) == 0) {
          done = false;
          for (int k = 0, _n = (2); k < _n; k = k + 1) {
            int tmp = length + k == 0 ? f[i] : ___next[f[i]][j][length + k];
            minimize(f[i | ((k + 1) << (2 * j))], tmp);
          }
        }
      }
      if (done) maximize(res, 8 * length + value);
    }
  return res;
}
void process(void) {
  int res = -1;
  for (int i = 0, _n = (n / 8 + 1); i < _n; i = i + 1) maximize(res, maxSeq(i));
  printf("%d\n", res);
}
int main(void) {
  init();
  prepare();
  process();
  return 0;
}
