#include <iostream>
#include <cstdio>
#include <cstring>
#define MAXN 200005
//#define ivorysi
using namespace std;
typedef long long int64;
typedef double db;
const int MOD = 1000000007;
int N,A[MAXN],x[MAXN],st[MAXN],ed[MAXN];
int64 cnt[MAXN],V[MAXN],D[MAXN],ID[MAXN],S,tr[MAXN],tr_cnt[MAXN],Inv_2,ans;
int64 fpow(int64 x,int64 c) {
    int64 res = 1,t = x;
    while(c) {
        if(c & 1) res = res * t % MOD;
        t = t * t % MOD;
        c >>= 1;
    }
    return res;
}
int lowbit(int x) {return x & (-x);}
void insert(int x,int64 v) {
    while(x <= N) {
        tr[x] += v;
        tr[x] %= MOD;
        tr_cnt[x]++;
        x += lowbit(x);
    }
}
int64 Query(int x,int64 v) {
    int64 res = 0;
    while(x > 0) {
        res += tr[x];
        x -= lowbit(x);
    }
    res %= MOD;
    return res * v % MOD;
}
int64 getnum(int x) {
    int64 res = 0;
    while(x > 0) {
        res += tr_cnt[x];
        x -= lowbit(x);
    }
    return res;
}
int64 Query_range(int L,int R,int64 v) {
    if(L == 0) ++L;
    if(L > R) return 0;
    return (Query(R,v) + MOD - Query(L - 1,v)) % MOD;
}
void Solve() {
    scanf("%d",&N);
    for(int i = 1 ; i <= N ; ++i) scanf("%d",&A[i]),cnt[A[i]]++;
    for(int i = N - 1; i >= 1 ; --i) cnt[i] += cnt[i + 1];
    S = 1;Inv_2 = (MOD + 1) / 2;
    for(int i = 1 ; i <= N ; ++i) {
        cnt[i] -= N - i;
        if(cnt[i] <= 0) {puts("0");return;}
        S = S * cnt[i] % MOD;
    }
    for(int i = 1 ; i <= N ; ++i) {
        V[i] = (cnt[i] - 1) * fpow(cnt[i],MOD - 2) % MOD;
    }
    D[0] = 1;
    st[0] = 0;
    for(int i = 1 ; i <= N ; ++i) {
        x[i] = x[i - 1];D[i] = D[i - 1];
        if(V[i] == 0) {x[i]++;st[x[i]] = i;ed[x[i] - 1] = i - 1;}
        else D[i] = D[i] * V[i] % MOD;
        ID[i] = fpow(D[i],MOD - 2);
    }
    ed[x[N]] = N;
    for(int i = 1 ; i <= N ; ++i) {
        ans += Query_range(st[x[A[i]]],A[i],D[A[i]] * S % MOD * Inv_2 % MOD);
        ans %= MOD;
        insert(A[i],ID[A[i]]);
    }
    memset(tr,0,sizeof(tr));
    memset(tr_cnt,0,sizeof(tr_cnt));
    for(int i = 1 ; i <= N ; ++i) {
        int64 t = Query_range(A[i] + 1,ed[x[A[i]]],ID[A[i]] * S % MOD * Inv_2 % MOD);
        ans += ((getnum(N) - getnum(A[i])) * S % MOD + MOD - t) % MOD;
        ans %= MOD;
        insert(A[i],D[A[i]]);
    }
    printf("%lld\n",ans);
}
 
int main() {
    Solve();
    return 0;
}