// #define DEBUGGING #include #define endl '\n' #define ALL(V) (V).begin(), (V).end() #define ALLR(V) (V).rbegin(), (V).rend() using ll = std::int64_t; using ull = std::uint64_t; using PLL = std::pair; using TLL = std::tuple; template using V = std::vector; template using VV = V>; 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...)); } 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...); } template const T& clamp(const T &t, const T &low, const T &high) { return std::max(low, std::min(high, t)); } template void chclamp(T &t, const T &low, const T &high) { return t = clamp(t, low, high); } 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; } #define mv_rec make_v(init, tail...) template T make_v(T init) { return init; } template auto make_v(T init, size_t s, Tail... tail) { return V(s, mv_rec); } #undef mv_rec using namespace std; #ifdef DEBUGGING #include "../../debug/debug.cpp" #else #define DEBUG(...) 0 #define DEBUG_SEPARATOR_LINE 0 #endif const ll inf = 5e15; // 0-indexed // [l, r) template struct Bit { V data; T id_ele; Bit(ll size, T id_ele) : id_ele(id_ele) { ll bsize = 1; while(bsize < size) bsize *= 2; data = V(bsize + 1, id_ele); } T sum(ll pos) { T ret = id_ele; for(; 0 < pos; pos -= pos & -pos) ret += data[pos]; return ret; } T sum(ll l, ll r) { if (r <= l) return 0; return sum(r) - sum(l); } void add(ll pos, T delta) { for(++pos; pos < data.size(); pos += pos & -pos) data[pos] += delta; } }; int main() { ll N; cin >> N; V A(N); for (ll &e : A) cin >> e; sort(ALL(A)); Bit bit(N + 10, 0); for (ll i = 0; i < N; i++) bit.add(i, A[i]); ll ans = -inf; for (ll i = 0; i < N; i++) { ll m = A[i]; ll lrest = i; ll rrest = (N - 1) - i; ll ok = 0, ng = min(lrest, rrest) + 1; while (abs(ok - ng) > 1) { ll mid = (ok + ng) / 2; ll l = A[i - mid]; ll r = A[N - mid]; ll inc = r - m, dec = m - l; (dec <= inc ? ok : ng) = mid; } ll tmp = m; tmp += bit.sum(i - ok, i); tmp += bit.sum(N - ok, N); tmp -= m * (2 * ok + 1); DEBUG(make_tuple(i, tmp, ok)); chmax(ans, tmp); } for (ll i = 0; i < N - 1; i++) { ll m1 = A[i], m2 = A[i + 1]; ll lrest = i, rrest = (N - 1) - (i + 1); ll ok = 0, ng = min(lrest, rrest) + 1; while (abs(ok - ng) > 1) { ll mid = (ok + ng) / 2; ll l = A[i - mid]; ll r = A[N - mid]; ll inc = 2 * r - (m1 + m2), dec = (m1 + m2) - 2 * l; (dec <= inc ? ok : ng) = mid; } ll tmp = m1 + m2; tmp += bit.sum(i - ok, i); tmp += bit.sum(N - ok, ok); tmp -= (m1 + m2) * (ok + 1); DEBUG(tmp); chmax(ans, tmp); } cout << ans << endl; return 0; }