#include <bits/stdc++.h>
using namespace std;
int n, min_cnt;
vector<int> idx[9];
vector<int> cur, st;
vector<map<int, int>> stm;
int dfs() {
  if (cur.empty()) {
    if (stm.back().empty()) return -1;
    return stm.back().rbegin()->first;
  }
  int ans = -1;
  for (size_t i = 0; i < cur.size(); ++i) {
    swap(cur[i], cur.back());
    st.push_back(cur.back());
    cur.pop_back();
    map<int, int> stm1;
    if (stm.empty()) {
      if ((int)idx[st.back()].size() >= min_cnt) {
        stm1[min_cnt] = min_cnt == 0 ? -1 : idx[st.back()][min_cnt - 1];
      }
      if ((int)idx[st.back()].size() >= min_cnt + 1) {
        stm1[min_cnt + 1] = idx[st.back()][min_cnt];
      }
    } else
      for (auto p : stm.back()) {
        size_t pos = upper_bound(idx[st.back()].begin(), idx[st.back()].end(),
                                 p.second) -
                     idx[st.back()].begin();
        if (min_cnt == 0) {
          if (!stm1.count(p.first)) {
            stm1[p.first] = p.second;
          } else {
            int& z = stm1[p.first];
            z = min(z, p.second);
          }
        } else if (pos + min_cnt - 1 < idx[st.back()].size()) {
          if (!stm1.count(p.first + min_cnt)) {
            stm1[p.first + min_cnt] = idx[st.back()][pos + min_cnt - 1];
          } else {
            int& z = stm1[p.first + min_cnt];
            z = min(z, idx[st.back()][pos + min_cnt - 1]);
          }
        }
        if (pos + min_cnt < idx[st.back()].size()) {
          if (!stm1.count(p.first + min_cnt + 1)) {
            stm1[p.first + min_cnt + 1] = idx[st.back()][pos + min_cnt];
          } else {
            int& z = stm1[p.first + min_cnt + 1];
            z = min(z, idx[st.back()][pos + min_cnt]);
          }
        }
      }
    stm.push_back(stm1);
    ans = max(ans, dfs());
    cur.push_back(st.back());
    st.pop_back();
    stm.pop_back();
    swap(cur[i], cur.back());
  }
  return ans;
}
int f(int m) {
  min_cnt = m;
  cur.clear();
  for (int i = 1; i < 9; ++i) cur.push_back(i);
  st.clear();
  stm.clear();
  return dfs();
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  for (int i = 0, v; i < n; ++i) {
    cin >> v;
    idx[v].push_back(i);
  }
  int lo = 0, hi = n;
  while (lo < hi) {
    int mid = (hi + lo) / 2;
    if (f(mid) > -1)
      lo = mid + 1;
    else
      hi = mid;
  }
  cout << f(lo - 1) << '\n';
}
