#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Yay!! #define endl codeforces // macros for iterator #define ALL(v) std::begin(v), std::end(v) #define ALLR(v) std::rbegin(v), std::rend(v) // alias using ll = std::int64_t; using ull = std::uint64_t; using pii = std::pair; using tii = std::tuple; using pll = std::pair; using tll = std::tuple; template using vec = std::vector; template using vvec = vec>; // variadic min/max template const T& var_min(const T &t) { return t; } template const T& var_max(const T &t) { return t; } template const T& var_min(const T &t, const Tail&... tail) { return std::min(t, var_min(tail...)); } template const T& var_max(const T &t, const Tail&... tail) { return std::max(t, var_max(tail...)); } // variadic chmin/chmax template void chmin(T &t, const Tail&... tail) { t = var_min(t, tail...); } template void chmax(T &t, const Tail&... tail) { t = var_max(t, tail...); } // multi demension array template struct multi_dim_array { using type = std::array::type, Head>; }; template struct multi_dim_array { using type = std::array; }; template using mdarray = typename multi_dim_array::type; // fill container template void fill_seq(T &t, F f, Args... args) { if constexpr (std::is_invocable::value) { t = f(args...); } else { for (ssize_t i = 0; i < t.size(); i++) fill_seq(t[i], f, args..., i); } } // make multi dimension vector template vec make_v(ssize_t sz) { return vec(sz); } template auto make_v(ssize_t hs, Tail&&... ts) { auto v = std::move(make_v(std::forward(ts)...)); return vec(hs, v); } // init namespace init__ { struct InitIO { InitIO() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << std::fixed << std::setprecision(30); } } init_io; } ll solve() { ll n; std::cin >> n; vec av(n); for (ll &e : av) { std::cin >> e; e--; } vvec idxv(n); for (ll i = 0; i < n; i++) idxv[av[i]].push_back(i); vec ng(n, 0); vec ngv; for (ll i = 0; i < n; i++) { const auto &v = idxv[i]; for (ll j = 0; j + 1 < v.size(); j++) if (v[j] + 1 < v[j + 1]) ng[i]++; if (1 < ng[i]) return -1; if (ng[i] == 1) ngv.push_back(i); } if (2 <= ngv.size()) return -1; if (ngv.size() == 0) return 0; ll i = ngv[0]; if (idxv[i].front() == 0 && idxv[i].back() == n - 1) return 1; return -1; } int main() { std::cout << solve() << "\n"; return 0; }