#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int mod=1000000007,inv2=500000004;
inline int kpow(int a,int b)
{
	int s=1;
	for(;b;b>>=1,a=1ll*a*a%mod)
		if(b&1)s=1ll*s*a%mod;
	return s;
}
inline void add(int &x,int y){(x+=y)>=mod?x-=mod:0;}
int n,a[200020],cnt[200020],inv[200020],D[200020],s,ans,cnt0[200020],lp[200020],rp[200020];
struct BIT
{
	int sum[200020];
	inline void ins(int p,int w){while(p<=n)add(sum[p],w),p+=p&-p;}
	inline int query(int p)
	{
		int s=0;
		while(p)add(s,sum[p]),p-=p&-p;
		return s;
	}
}t1,t2,t3;
int main()
{
	scanf("%d",&n);
	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)scanf("%d",&a[i]),++cnt[a[i]];
	s=1;
	for(int i=n;i;--i)cnt[i]+=cnt[i+1];
	for(int i=1;i<=n;++i)
	{
		cnt[i]-=(n-i);
		s=1ll*s*cnt[i]%mod;
		if(cnt[i]<=0)
		{
			printf("0");
			return 0;
		}
	}
	D[0]=1;
	for(int i=1;i<=n;++i)
	{
		D[i]=1ll*(cnt[i]-1)*inv[cnt[i]]%mod;
		if(!D[i])cnt0[i]=cnt0[i-1]+1,D[i]=D[i-1];
		else cnt0[i]=cnt0[i-1],D[i]=1ll*D[i]*D[i-1]%mod;
	//	printf("%d %d %d\n",cnt[i],D[i],cnt0[i]);
	}
	lp[0]=1;
	for(int i=1;i<=n;++i)
	{
		if(cnt0[i]!=cnt0[i-1])lp[i]=i;
		else lp[i]=lp[i-1];
	}
	for(int i=n;i;--i)
	{
		if(cnt0[i]!=cnt0[i+1])rp[i]=i;
		else rp[i]=rp[i+1];
	}
	for(int i=1;i<=n;++i)
	{
		int dv=kpow(D[a[i]],mod-2);
		ans=(ans+1ll*D[a[i]]*(t1.query(a[i])+mod-t1.query(lp[a[i]]-1)))%mod;
		ans=(ans+(t3.query(n)-t3.query(a[i]))*2-1ll*dv*(t2.query(rp[a[i]])+mod-t2.query(a[i])))%mod;
		t1.ins(a[i],dv);
		t2.ins(a[i],D[a[i]]);
		t3.ins(a[i],1);
	}
	ans=1ll*ans*s%mod*inv2%mod;
	if(ans<0)ans+=mod;
	printf("%d",ans);
	return 0;
}
