#pragma region Macros // #pragma GCC target("avx2") #pragma GCC optimize("O3") #include #include #include #include using namespace std; using namespace __gnu_pbds; template using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; struct __INIT{__INIT(){cin.tie(0);ios::sync_with_stdio(false);cout<=0;i--) #define FOR(i,a,b) for(ll i=a;i<=ll(b);i++) #define FORD(i,a,b) for(ll i=a;i>=ll(b);i--) #define overload4(_1,_2,_3,_4,name,...) name #define overload3(_1,_2,_3,name,...) name #define rep1(n) for(ll i=0;i(a);) #define rrep4(i,a,b,c) for(ll i=(a)+((b)-(a)-1)/(c)*(c);i>=(a);i-=c) #define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__) #define ALL(v) v.begin(), v.end() #define endl "\n" #define fi first #define se second #define popcount(bit) __builtin_popcount(bit) #define popcountll(bit) __builtin_popcountll(bit) #define pb push_back #define eb emplace_back using namespace atcoder; using P = pair; using PL = pair; using Graph = vector>; typedef long long ll; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } inline void Yes(bool b = true) { cout << (b ? "Yes" : "No") << '\n'; } inline void YES(bool b = true) { cout << (b ? "YES" : "NO") << '\n'; } inline void OKNG(bool b = true) { cout << (b ? "OK" : "NG") << '\n'; } const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; const int fx[8] = {0, 1, 1, 1, 0, -1, -1, -1}; const int fy[8] = {1, 1, 0, -1, -1, -1, 0, 1}; template const auto INF = numeric_limits::max()/2; int main() { ll n; cin >> n; vector P(n); ll ans = 0; ll tmp1 = 0; rep(i, n){ cin >> P[i]; if(P[i] != n)tmp1 += (i + 1); else tmp1 -= (i + 1); } set st; rep(i, n)st.insert(i + 1); rrep(i, n){ if(P[i] + 1 <= n && st.find(P[i] + 1) != st.end()){ ans += (i + 1); st.erase(P[i] + 1); }else { auto it = st.lower_bound(P[i]); if(it == st.end()){ it = st.begin(); } ll b = *it; if(b > P[i]){ ans += (i + 1); }else if(b < P[i]){ ans -= (i + 1); } st.erase(it); } } st.clear(); chmax(ans, 0LL); chmax(ans, tmp1); cout << ans << endl; }