//Keep pluggin',this is your only outlet.
#include<bits/stdc++.h>
#define MM(x,y) memset(x,y,sizeof(x))
#define MCPY(a,b) memcpy(a,b,sizeof(b))
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,b,a) for(int i=b;i>=a;i--)
#define fi first
#define mp make_pair
#define se second
using namespace std;
#define int long long

inline int quickpow(int m,int n,int p){int b=1;while(n){if(n&1)b=b*m%p;n=n>>1;m=m*m%p;}return b;}
inline int quickmul(int x,int y,int mod){return (x*y-(int)((long double)x/mod*y)*mod+mod)%mod;}
inline int getinv(int x,int p){return quickpow(x,p-2,p);}
inline int read(void){
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){f=ch=='-'?-1:1;ch=getchar();}
    while(isdigit(ch)){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
    return x * f;
}
const int Mod = 1e9 + 7;
const int MAXN = 2e5 + 100;
#define lowbit(x) (x&-x)

struct BIT {
    int c[MAXN];
    inline void reset(void){memset(c,0,sizeof(c));}
    inline void add(int x,int d){for (int i = x; i < MAXN; i += lowbit(i)) c[i] = (c[i] + d) % Mod;}
    inline int sum(int x){int ret = 0; for (int i = x; i >= 1; i -= lowbit(i)) ret = (ret + c[i]) % Mod; return ret;}
}c1,c2;
int tot = 1,S[MAXN],a[MAXN],inv2 = (Mod + 1) / 2,_00man[MAXN],cnt[MAXN],D[MAXN],invD[MAXN],n;
inline void upd(int &x,int y){x = (x + y) % Mod;}
///------------------head------------------
signed main(signed argc, char *argv[]){
    n = read();
    rep(i,1,n) a[i] = read(),cnt[a[i]]++;
    for (int i = n - 1; i >= 1; i--) cnt[i] += cnt[i + 1];
    for (int i = 1; i <= n; ++i) cnt[i] -= (n - i);
    S[0] = D[0] = 1;
    for (int i = 1; i <= n; i++) {
        if (cnt[i] <= 0) return puts("0"),0;
        tot = tot * cnt[i] % Mod;
    }
    for (int i = 1; i <= n; ++i) {
        int x = (cnt[i] - 1) * getinv(cnt[i],Mod) % Mod;
        if (x == 0) {
            _00man[i] = _00man[i-1] + 1;
            S[_00man[i]] = i;
            D[i] = D[i-1];
        }
        else {
            _00man[i] = _00man[i-1];
            D[i] = D[i-1] * x % Mod;
        }
        invD[i] = getinv(D[i],Mod);
    }
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        upd(ans,(c1.sum(a[i])-c1.sum(S[_00man[a[i]]] - 1) + Mod) * D[a[i]] % Mod * tot % Mod * inv2 % Mod);
        c1.add(a[i],invD[a[i]]);
        c2.add(a[i],1);
    }
    c1.reset(); c2.reset();
    for (int i = n; i >= 1; --i) {
        upd(ans,(Mod-1) * (c1.sum(a[i] - 1) - c1.sum(S[_00man[a[i]]] - 1) + Mod) % Mod * D[a[i]] % Mod * tot % Mod * inv2 % Mod);
        upd(ans,c2.sum(a[i] - 1) * tot % Mod);
        c1.add(a[i],invD[a[i]]);
        c2.add(a[i],1);
    }
    printf("%lld\n",ans);
    return 0;
}

/* Examples: */
/*

*/

/*

*/
