#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 upd(int x){return x+(x>>31&Mod);}
int inv[200010];

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