#include<cstdio>
#include<algorithm>
#include<cctype>
using namespace std;
#define G getchar()
int read()
{
	int x=0; char ch=G;
	for (;!isdigit(ch);ch=G);
	for (;isdigit(ch);ch=G) x=(x<<3)+(x<<1)+(ch^48);
	return x;
}
#undef G
typedef long long ll;
const int Mod=1e9+7,inv2=Mod+1>>1;
int qpow(int x,int y=Mod-2){
	int res=1;
	for (;y;y>>=1,x=1LL*x*x%Mod)
		if (y&1) res=1LL*res*x%Mod;
	return res;
}

int n,a[200010],cnt[200010],ans;
int pos[200010],postot; int D[200010];
int tri1[200010],tri2[200010],tri3[200010];
void add(int x,int b,int c){
	for (;x<=n;x+=x&-x){
		tri1[x]++;
		tri2[x]=(tri2[x]+b)%Mod;
		tri3[x]=(tri3[x]+c)%Mod;
	}
}
int ask(int *tri,int x){
	int res=0;
	for (;x;x-=x&-x) res=(res+tri[x])%Mod;
	return res;
}
int main()
{
	n=read();
	for (int i=1;i<=n;i++) cnt[a[i]=read()]++;
	int sametot=0,tot=1;
	for (int i=n;i;i--){
		sametot=(sametot+1LL*cnt[i]*(cnt[i]-1)/2)%Mod;
		cnt[i]+=cnt[i+1];
		tot=1LL*tot*(cnt[i]-n+i)%Mod;
	}
	if (tot==0) return puts("0"),0;
	ans=1LL*sametot*tot%Mod*inv2%Mod;
	D[0]=1;
	for (int i=1;i<=n;i++){
		D[i]=D[i-1];
		if (cnt[i]-1-n+i) D[i]=1LL*D[i]*(cnt[i]-1-n+i)%Mod*qpow(cnt[i]-n+i)%Mod;
		else pos[++postot]=i;
	}
	for (int i=1;i<=n;i++){
		int l=(!postot||pos[1]>a[i]?1:pos[upper_bound(pos+1,pos+postot+1,a[i])-pos-1]),r=a[i]-1;
		if (l<=r) ans=(ans+1LL*tot*inv2%Mod*D[a[i]]%Mod*(ask(tri3,r)-ask(tri3,l-1)))%Mod;
		l=a[i]+1,r=(!postot||pos[postot]<=a[i]?n:pos[upper_bound(pos+1,pos+postot+1,a[i])-pos]-1);
		if (l<=r) ans=(ans-1LL*tot*inv2%Mod*qpow(D[a[i]])%Mod*(ask(tri2,r)-ask(tri2,l-1)))%Mod;
		add(a[i],D[a[i]],qpow(D[a[i]]));
		ans=(ans+1LL*tot*(i-ask(tri1,a[i])))%Mod;
	}
	printf("%d\n",(ans+Mod)%Mod);
	return 0;
}