#include <bits/stdc++.h>
const int N=200005,mu=1e9+7,inv2=(mu+1)/2;
int s[N],a[N],n,S,T[N],c[N],ans,d[N],zero[N];
void reduce(int &x) { x+=x>>31&mu; }
int ksm(int x,int y){
	int ans=1;
	for (;y;y>>=1,x=x*1ll*x%mu)
		if (y&1) ans=ans*1ll*x%mu;
	return ans;
}
int lowbit(int x){
	return x&(-x);
}
void upd(int x,int y){
	while (x<=n){
		reduce(c[x]+=y-mu);
		x=x+lowbit(x);
	}
}
int getsum(int x){
	int res=0;
	while (x>0){
		reduce(res+=c[x]-mu);
		x-=lowbit(x);
	}
	return res;
}
void upd2(int x,int y){
	while (x<=n){
		reduce(d[x]+=y-mu);
		x=x+lowbit(x);
	}
}
int getsum2(int x){
	int res=0;
	while (x>0){
		reduce(res+=d[x]-mu);
		x-=lowbit(x);
	}
	return res;
}
int solve(){
	int res=0;
	memset(c,0,sizeof(c));
	for (int i=n;i>=1;i--){
		reduce(res+=getsum(a[i]-1)-mu);
		upd(a[i],1);
	}
	return res;
}
int main(){
	scanf("%d",&n);
	for (int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		s[a[i]]++;
	}
	S=1;
	for (int i=n-1;i;i--) s[i]+=s[i+1]-1;
	for (int i=1;i<=n;i++) {//总个数 
		if (s[i]<=0){
			puts("0");
			return 0;		
		}
		S=S*1ll*s[i]%mu;
	}
	T[0]=1;
	for (int i=1;i<=n;i++) {
		zero[i]=zero[i-1];
		if (s[i]-1==0) T[i]=T[i-1],zero[i]++;
		else T[i]=T[i-1]*1ll*(s[i]-1)%mu*ksm(s[i],mu-2)%mu;
	}
	int sum=0; 
	for (int i=n;i>=1;i--){//a[i]<=a[j] 
		int t=(sum-getsum(a[i]-1)-(sum-getsum2(zero[a[i]]))+mu)%mu;
		ans=(ans+t*1ll*S%mu*ksm(T[a[i]],mu-2))%mu;
		reduce(sum+=T[a[i]]-mu);
		upd(a[i],T[a[i]]);
		upd2(zero[a[i]],T[a[i]]);
	}
	ans=ans*1ll*inv2%mu;
	memset(c,0,sizeof(c)),memset(d,0,sizeof(d)),sum=0;
	for (int i=1;i<=n;i++){//a[i]>a[j] 从a[i]->a[j] 
		int t=(sum-getsum(a[i])-(sum-getsum2(zero[a[i]]))+mu)%mu;
		ans=(ans-t*1ll*inv2%mu*S%mu*ksm(T[a[i]],mu-2))%mu;
		reduce(sum+=T[a[i]]-mu);
		upd(a[i],T[a[i]]);
		upd2(zero[a[i]],T[a[i]]);
	}
	ans=(ans+solve()*1ll*S)%mu;
	printf("%d\n",ans);
} 