#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5,mod=1e9+7,inv2=(mod+1)/2;
inline int pls(int x,int y){
	x+=y;return x>=mod?x-mod:x;
} 
inline int dec(int x,int y){
	x-=y;return x<0?x+mod:x;
}
inline int mul(int x,int y){return 1ll*x*y%mod;}
inline int qpow(int a,int b){
	int res=1;
	for(;b;b>>=1,a=mul(a,a)) if(b&1) res=mul(res,a);
	return res;
}
inline int read(){
	int s=0;char ch=getchar();
	while(!isdigit(ch)) ch=getchar();
	while(isdigit(ch)) s=s*10+ch-'0',ch=getchar();
	return s;
}
int n;
int a[N],cnt[N],d[N],zero[N],p[N];
int tot=1;
int c1[N],c2[N];
inline void add(int x,int y){
	for(;x<=n;x+=x&-x) c1[x]=pls(c1[x],y),c2[x]++; 
}
inline int qry(int *c,int x){
	int s=0;
	for(;x;x-=x&-x) s=pls(s,c[x]);
	return s;
}
int main(){
	n=read();
	for(int i=1;i<=n;i++) a[i]=read(),cnt[a[i]]++;
	for(int i=n-1;i>=1;i--) cnt[i]+=cnt[i+1];
	for(int i=1;i<=n;i++){
		cnt[i]-=(n-i);
		if(cnt[i]<=0) {puts("0");return 0;}
		tot=mul(tot,cnt[i]);
	}
	p[0]=d[0]=1;
	for(int i=1;i<=n;i++){
		int u=mul(cnt[i]-1,qpow(cnt[i],mod-2));
		d[i]=d[i-1],zero[i]=zero[i-1];
		if(!u) zero[i]++,p[zero[i]]=i;
		else d[i]=mul(d[i],u);
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		ans=pls(ans,mul(dec(qry(c1,a[i]),qry(c1,p[zero[a[i]]]-1)),mul(d[a[i]],mul(tot,inv2))));
		add(a[i],qpow(d[a[i]],mod-2));
	}
	memset(c1,0,sizeof(c1));memset(c2,0,sizeof(c2));
	for(int i=n;i>=1;i--){
		ans=dec(ans,mul(dec(qry(c1,a[i]-1),qry(c1,p[zero[a[i]]]-1)),mul(d[a[i]],mul(tot,inv2))));
		ans=pls(ans,mul(qry(c2,a[i]-1),tot));
		add(a[i],qpow(d[a[i]],mod-2));
	}
	printf("%d",ans);
	return 0;
} 