#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e5;
const ll mod=1e9+7;
ll a[maxn+5],num[maxn+5],cnt[maxn+5],S,D[maxn+5];
int pre[maxn+5],suf[maxn+5];
int n;
ll c[2][maxn+5];
ll ans=0;
ll Pow(ll a,ll b,ll mod)
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
ll inv(ll a)
{
    return Pow(a,mod-2,mod);
}
int lowbit(int x)
{
    return x&(-x);
}
ll add(ll *c,int k,ll data)
{
    for(;k<=n+1;k+=lowbit(k)) c[k]=(c[k]+data)%mod;
}
ll query(ll *c,int k)
{
    ll ans=0;
    for(;k;k-=lowbit(k)) ans=(ans+c[k])%mod;
    return ans;
}
int main()
{

    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%lld",&a[i]),++num[a[i]];
    for(int i=n-1;i>=1;--i) num[i]+=num[i+1];
    S=1;
    D[0]=1;
    for(int i=1;i<=n;++i)
    {
        cnt[i]=num[i]-(n-i),S=S*cnt[i]%mod;
        if(cnt[i]<=0) return 0*printf("0\n");
        D[i]=D[i-1];
        if(cnt[i]>1) D[i]=D[i]*(cnt[i]-1)%mod*inv(cnt[i])%mod,pre[i]=pre[i-1];else pre[i]=i;
    }
    suf[n]=n;
    for(int i=n-1;i>=1;--i)
        if(cnt[i]>1)
        {
            if(cnt[i+1]>1) suf[i]=suf[i+1];else suf[i]=i;
        }
        else suf[i]=i;
   // for(int i=1;i<=n;++i) printf("pre : %d suf : %d\n",pre[i],suf[i]);
   // for(int i=1;i<=n;++i) printf("%lld ",cnt[i]);printf("\n");
   // printf("%lld\n",S);
   // for(int i=1;i<=n;++i) printf("%lld ",D[i]);printf("\n");
    for(int i=1;i<=n;++i)
    {
        ans=(ans+(query(c[0],a[i])-query(c[0],pre[a[i]]-1))%mod*S%mod*D[a[i]]%mod*inv(2LL)%mod)%mod;
        if(ans<0) ans+=mod;
        add(c[0],a[i],inv(D[a[i]]));
    }
    for(int i=1;i<=n;++i) c[0][i]=0;
    for(int i=1;i<=n;++i)
    {
       // if(D[a[i]]==0) continue;
        ans=(ans+S*(query(c[1],n)-query(c[1],a[i]))%mod-inv(2LL)*S%mod*inv(D[a[i]])%mod*(query(c[0],suf[a[i]])-query(c[0],a[i]))%mod)%mod;
        if(ans<0) ans+=mod;
        add(c[0],a[i],D[a[i]]);
        add(c[1],a[i],1LL);
    }
    printf("%lld\n",ans);
    return 0;
}
