#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
    int x=0,w=1;char ch=getchar();
    while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if (ch=='-') w=0,ch=getchar();
    while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
const int N = 2e5+5;
const int mod = 1e9+7;
int n,a[N],cnt[N],S=1,z[N],st[N],D[N],ID[N],c1[N],c2[N];
int fastpow(int a,int b){
    int res=1;
    while (b) {if (b&1) res=1ll*res*a%mod;a=1ll*a*a%mod;b>>=1;}
    return res;
}
void mdf(int k,int v){while(k<=n)c1[k]=(c1[k]+v)%mod,++c2[k],k+=k&-k;}
int qry1(int k){int s=0;while(k)s=(s+c1[k])%mod,k^=k&-k;return s;}
int qry2(int k){int s=0;while(k)s+=c2[k],k^=k&-k;return s;}
int main(){
    n=gi();
    for (int i=1;i<=n;++i) ++cnt[a[i]=gi()];
    for (int i=n;i>=1;--i) cnt[i]+=cnt[i+1];
    for (int i=1;i<=n;++i){
        cnt[i]-=n-i;
        if (cnt[i]<=0) return puts("0"),0;
        S=1ll*S*cnt[i]%mod;
    }
    st[0]=D[0]=1;
    for (int i=1;i<=n;++i){
        int x=1ll*(cnt[i]-1)*fastpow(cnt[i],mod-2)%mod;
        if (!x) st[z[i]=z[i-1]+1]=i,D[i]=D[i-1];
        else z[i]=z[i-1],D[i]=1ll*D[i-1]*x%mod;
        ID[i]=fastpow(D[i],mod-2);
    }
    int inv2=(mod+1)>>1,ans=0;
    for (int i=1;i<=n;++i){
        ans=(ans+1ll*(qry1(a[i])-qry1(st[z[a[i]]]-1)+mod)*D[a[i]]%mod*S%mod*inv2)%mod;
        mdf(a[i],ID[a[i]]);
    }
    memset(c1,0,sizeof(c1)),memset(c2,0,sizeof(c2));
    for (int i=n;i;--i){
        ans=(ans-1ll*(qry1(a[i]-1)-qry1(st[z[a[i]]]-1)+mod)*D[a[i]]%mod*S%mod*inv2%mod+mod)%mod;
        ans=(ans+1ll*qry2(a[i]-1)*S)%mod;
        mdf(a[i],ID[a[i]]);
    }
    printf("%d\n",ans);
    return 0;
}