#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstdlib>
#define LL long long
#define LD long double
using namespace std;
const int NN=200000 +117;
const int MM=100000 +117;
int read(){
	int fl=1,x;char c;
	for(c=getchar();(c<'0'||c>'9')&&c!='-';c=getchar());
	if(c=='-'){fl=-1;c=getchar();}
	for(x=0;c>='0'&&c<='9';c=getchar())
		x=(x<<3)+(x<<1)+c-'0';
	return x*fl;
}
void open(){
	freopen("a.in","r",stdin);
	//freopen("a.out","w",stdout);
}
void close(){
	fclose(stdin);
	fclose(stdout);
}
const int mod=1e9+7;
LL ksm(LL a,int b){
	LL ret=1;
	for(;b;b>>=1,a=a*a%mod)
		if(b&1)ret=ret*a%mod;
	return ret;
}

int m,n;
int a[NN]={};
int cnt[NN]={};
int cha[NN]={};
int zer[NN]={};
LL ni[NN]={};
int xt[NN]={};
LL val[NN]={};
LL bit[NN]={};
LL bef[NN]={};
inline int lowbit(int x){
	return x&-x;
}
LL q(LL bit[],int x){
	LL ret=0;
	for(;x;x-=lowbit(x)){
		ret+=bit[x];
	}
	return ret%mod;
}
LL query(LL bit[],int l,int r){
	if(r<l)return 0;
	return (q(bit,r)-q(bit,l-1))%mod;
}
void add(LL bit[],int x,LL v){
	for(;x<=n;x+=lowbit(x)){
		bit[x]=(bit[x]+v)%mod;
	}
}
int main(){
	//open();
	n=read();
	for(int i=1;i<=n;++i){
		a[i]=read();
		cnt[a[i]]++;
	}
	for(int i=n;i>=1;--i)cnt[i-1]+=cnt[i];
	bool fl=0;
	LL all=1;
	for(int i=1;i<=n;++i){
		cnt[i]-=n-i;
		all=all*cnt[i]%mod;
		if(cnt[i]<=0)fl=1;
		cha[i]=cnt[i]-1;
		if(!cha[i]){
			cha[i]=1;
			zer[i]=1;
		}
	}
	if(fl){
		printf("0\n");
		return 0;
	}
	ni[1]=1;
	for(int i=2;i<=n;++i){
		ni[i]=-(mod/i)*ni[mod%i]%mod;
	}
	xt[n]=n;
	for(int i=n-1;i>=0;--i){
		if(zer[i+1])xt[i]=i;
		else xt[i]=xt[i+1];
	}
	val[0]=1;
	for(int i=1;i<=n;++i){
		val[i]=val[i-1]*cha[i]%mod*ni[cnt[i]]%mod;
	}
	LL ans=0;
	for(int i=1;i<=n;++i){
		int k=a[i];
		int pos=xt[k];
		LL res=query(bit,a[i]+1,pos)*ksm(val[a[i]],mod-2)%mod;
		res=res*ni[2]%mod*all%mod;
		res=-res;
		res+=query(bef,a[i]+1,n)*all%mod;
		add(bit,a[i],val[a[i]]);
		add(bef,a[i],1);
		(ans+=res)%=mod;
	}
	for(int i=1;i<=n;++i)bit[i]=0;
	for(int i=n;i>=1;--i){
		int k=a[i];
		int pos=xt[k];
		LL res=query(bit,a[i],pos)*ksm(val[a[i]],mod-2)%mod;
		res=res*ni[2]%mod*all%mod;
		add(bit,a[i],val[a[i]]);
		(ans+=res)%=mod;
	}
	ans=(ans+mod)%mod;
	printf("%lld\n",ans);
	close();
	return 0;
}