#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1e9 + 7;
const int maxn = 2e5 + 10;
int A[maxn], cnt[maxn], st[maxn], ed[maxn];
LL D[maxn], C[maxn];

LL qpow(LL a, LL b) {
    LL ret = 1LL;
    while (b) {
        if (b & 1) ret = ret * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return ret;
}

LL inv(LL x) {
    return qpow(x, mod - 2);
}

LL c[2][maxn];
int lowbit(int s) {
    return s & (-s);
}
void modify(int o, int i, LL x) {
    while (i < maxn) c[o][i] = (c[o][i] + x) % mod, i += lowbit(i);
    return;
}
LL query(int o, int i) {
    LL ret = 0;
    while (i > 0) ret = (ret + c[o][i]) % mod, i -= lowbit(i);
    return ret;
}

int main() {
    int N;
    scanf("%d", &N);
    for (int i = 1; i <= N; ++i) scanf("%d", A + i), cnt[A[i]]++;
    for (int i = N; i >= 1; --i) cnt[i] += cnt[i + 1];
    LL S = 1;
    for (int i = 1; i <= N; ++i) {
        cnt[i] -= N - i;
        if (cnt[i] <= 0) S = 0;
        else S = S * cnt[i] % mod;
    }
    if (S == 0) {
        puts("0");
        return 0;
    }
    for (int i = N; i >= 1; --i) {
        if (i == N || cnt[i + 1] == 1 || cnt[i] == 1) st[i] = ed[i] = i;
        else st[i] = st[i + 1], ed[st[i]] = i;
    }
    for(int i = 1; i <= N; ++i){
        LL pre;
        if(ed[st[i]] == i) pre = 1;
        else pre = D[i-1];
        D[i] = pre * (cnt[i] - 1) % mod * inv(cnt[i]) % mod;
    }
    LL ans = 0;
    for (int j = 1; j <= N; ++j) {
        ans = (ans + C[A[j]]) % mod;
        C[A[j]]++;
        if(!D[A[j]]) continue;
        LL tmp = (query(0, A[j] - 1) - query(0, ed[st[A[j]]] - 2) + mod) % mod;
        ans = (ans + tmp * D[A[j]]) % mod;
        modify(0, A[j], inv(D[A[j]]));
    }
    memset(c[0], 0, sizeof(c[0]));
    LL sum = 0;
    for (int j = N; j >= 1; --j) {
        sum = (sum + query(1, A[j] - 1)) % mod;
        modify(1, A[j], 1);
        if(!D[A[j]]) continue;
        LL tmp = (query(0, A[j] - 1) - query(0, ed[st[A[j]]] - 2) + mod) % mod;
        ans = (ans - tmp * D[A[j]] % mod + mod) % mod;
        modify(0, A[j], inv(D[A[j]]));
    }
    ans = (ans * inv(2) % mod + sum) * S % mod;
    printf("%lld\n", ans);
    return 0;
}