#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<vector>
#include<algorithm>
#define mod 1000000007
typedef long long ll;
ll gi(){
	ll x=0,f=1;
	char ch=getchar();
	while(!isdigit(ch))f^=ch=='-',ch=getchar();
	while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
	return f?x:-x;
}
int pow(int x,int y){
	int ret=1;
	while(y){
		if(y&1)ret=1ll*ret*x%mod;
		x=1ll*x*x%mod;y>>=1;
	}
	return ret;
}
int n,A[200010],c[200010],C[200010],D[200010],iD[200010],d[200010],id[200010];
std::vector<int>vec[200010];
int t[200010],T[200010],from[200010];
void add(int&x,int y){x=x+y>=mod?x+y-mod:x+y;}
void update(int*t,int x,int y){while(x<=n)add(t[x],y),x+=x&-x;}
int query(int*t,int x){int r=0;while(x)add(r,t[x]),x-=x&-x;return r;}
int main(){
#ifdef XZZSB
	freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
#endif
	n=gi();
	for(int i=1;i<=n;++i)++c[A[i]=gi()];
	for(int i=n;i;--i)C[i]=c[i]+C[i+1];
	int S=1;
	for(int i=1;i<=n;++i)S=1ll*S*std::max(0,C[i]-n+i)%mod;
	if(!S)return puts("0"),0;
	for(int i=1;i<=n;++i)d[i]=1ll*(C[i]-n+i-1)*pow(C[i]-n+i,mod-2)%mod,id[i]=pow(d[i],mod-2);
	for(int i=1;i<=n;++i){
		from[i]=d[i]?from[i-1]:i;
		if(d[i-1])d[i]=1ll*d[i]*d[i-1]%mod,id[i]=1ll*id[i]*id[i-1]%mod;
	}
	for(int i=1;i<=n;++i)D[i]=d[A[i]],iD[i]=id[A[i]];
	int ans=0;
	for(int i=1;i<=n;++i)ans=(ans+1ll*c[i]*(c[i]-1)/2)%mod;
	ans=1ll*ans*S%mod*(mod+1>>1)%mod;
	for(int i=1;i<=n;++i)vec[from[A[i]]].push_back(i);
	for(int i=0;i<=n;++i){
		if(vec[i].empty())continue;
		for(int i:vec[i]){
			add(ans,1ll*D[i]*query(t,A[i]-1)%mod*S%mod*(mod+1>>1)%mod);
			update(t,A[i],iD[i]);
		}
		for(int i:vec[i])update(t,A[i],mod-iD[i]);
		std::reverse(vec[i].begin(),vec[i].end());
		for(int i:vec[i]){
			add(ans,(1ll*S*query(T,A[i]-1)%mod-1ll*S*D[i]%mod*query(t,A[i]-1)%mod*(mod+1>>1)%mod+mod)%mod);
			update(t,A[i],iD[i]);update(T,A[i],1);
		}
		for(int i:vec[i])update(t,A[i],mod-iD[i]),update(T,A[i],mod-1);
	}
	memset(t,0,sizeof t);
	for(int i=n;i;--i)add(ans,1ll*S*query(t,from[A[i]]-1)%mod),update(t,A[i],1);
	printf("%d\n",ans);
	return 0;
}
