#include <bits/stdc++.h>
#define REP(i,n) for (int i = 0; (i) < (n); ++(i))
#define REP3(i,m,n) for (int i = (m); (i) < (n); ++(i))
#define REP_R(i,n) for (int i = (int)(n) - 1; (i) >= 0; --(i))
#define ALL(x) begin(x), end(x)
using namespace std;
using ll = long long;
template <class T> inline void chmin(T & a, T const & b) { a = min(a, b); }

template <class Monoid>
struct segment_tree {
    typedef typename Monoid::underlying_type underlying_type;
    int n;
    vector<underlying_type> a;
    const Monoid mon;
    segment_tree() = default;
    segment_tree(int a_n, underlying_type initial_value = Monoid().unit(), Monoid const & a_mon = Monoid())
            : mon(a_mon) {
        n = 1; while (n < a_n) n *= 2;
        a.resize(2 * n - 1, mon.unit());
        fill(a.begin() + (n - 1), a.begin() + ((n - 1) + a_n), initial_value);
        REP_R (i, n - 1) a[i] = mon.append(a[2 * i + 1], a[2 * i + 2]);
    }

    void point_set(int i, underlying_type z) {
        assert (0 <= i and i < n);
        a[i + n - 1] = z;
        for (i = (i + n) / 2; i > 0; i/= 2) {
            a[i - 1] = mon.append(a[2 * i - 1], a[2 * i]);
        }
    }

    underlying_type range_concat(int l, int r) {
        assert (0 <= l and l <= r and r <= n);
        underlying_type lacc = mon.unit();
        underlying_type racc = mon.unit();
        for (l += n, r += n; l < r; l /= 2, r /= 2) {
            if (l % 2 == 1) lacc = mon.append(lacc, a[(l ++) - 1]);
            if (r % 2 == 1) racc = mon.append(a[(-- r) - 1], racc);
        }
        return mon.append(lacc, racc);
    }
};

struct plus_monoid {
    typedef int underlying_type;
    int unit() const { return 0; }
    int append(int a, int b) const { return a + b; }
};

ll solve(int n, vector<int> const & a) {
    int max_a = *max_element(ALL(a));
    vector<deque<int> > indices(max_a + 1);
    REP (i, n) indices[a[i]].push_back(i);

    segment_tree<plus_monoid> segtree(n, 1);
    ll cost = 0;
    REP (a_i, max_a + 1) {
        while (not indices[a_i].empty()) {
            int cost_l = segtree.range_concat(0, indices[a_i].front());
            int cost_r = segtree.range_concat(indices[a_i].back() + 1, n);
            if (cost_l < cost_r) {
                cost += cost_l;
                segtree.point_set(indices[a_i].front(), 0);
                indices[a_i].pop_front();
            } else {
                cost += cost_r;
                segtree.point_set(indices[a_i].back(), 0);
                indices[a_i].pop_back();
            }
        }
    }

    return cost;
}

int main() {
    int n; cin >> n;
    vector<int> a(n);
    REP (i, n) cin >> a[i];
    cout << solve(n, a) << endl;
    return 0;
}

