#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
const ll MOD=1e9+7,inv2=5e8+4;
int n,nxt[200005],a[200005],b[200005];
ll cnt[200005],pre[200005],suf[200005],s2[200005],c[200005];
ll quick_pow(ll x,ll a)
{
	ll ans=1;
	while(a)
	{
		if(a&1)ans=ans*x%MOD;
		x=x*x%MOD;
		a>>=1;
	}
	return ans;
}
void add(int p,ll v)
{
	while(p<=n)
	{
		c[p]+=v;
		if(c[p]>=MOD)c[p]-=MOD;
		p+=p^(p&(p-1));
	}
}
ll sum(int p)
{
	ll ans=0;
	while(p)
	{
		ans+=c[p];
		p&=p-1;
	}
	return ans%MOD;
}
ll sum(int l,int r)
{
	return sum(r)-sum(l-1);
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		b[i]=a[i];
		cnt[a[i]]++;
	}
	for(int i=n;i>=1;i--)cnt[i]+=cnt[i+1];
	for(int i=1;i<=n;i++)
	{
		cnt[i]-=n-i;
		if(cnt[i]<=0)
		{
			printf("0\n");
			return 0;
		}
	}
	pre[0]=1;
	for(int i=1;i<=n;i++)pre[i]=pre[i-1]*cnt[i]%MOD;
	suf[n+1]=1;
	for(int i=n;i>=1;i--)suf[i]=suf[i+1]*cnt[i]%MOD;
	for(int i=1;i<=n;i++)
	{
		if(cnt[i]==1)s2[i]=1;
		else s2[i]=s2[i-1]*(cnt[i]-1)%MOD;
	}
	ll ans=0;
	sort(b+1,b+n+1);
	for(int i=1;i<=n;)
	{
		int j=i;
		while(b[j]==b[i])j++;
		ans=(ans+1ll*(j-i)*(j-i-1)/2%MOD*pre[n]%MOD*inv2)%MOD;
		i=j;
	}
	nxt[n+1]=n+1;
	for(int i=n;i>=1;i--)
	{
		nxt[i]=nxt[i+1];
		if(cnt[i+1]==1)nxt[i]=i+1;
	}
	for(int i=n;i>=1;i--)
	{
		ll k=pre[a[i]]*quick_pow(s2[a[i]],MOD-2)%MOD;
		ans=(ans+k*sum(a[i]+1,nxt[a[i]]-1)%MOD*inv2)%MOD;
		add(a[i],suf[a[i]+1]*s2[a[i]]%MOD);
	}
	memset(c,0,sizeof(c));
	for(int i=1;i<=n;i++)
	{
		add(a[i],1);
		ans=(ans+sum(a[i]+1,n)*pre[n])%MOD;
	}
	nxt[0]=0;
	for(int i=1;i<=n;i++)
	{
		nxt[i]=nxt[i-1];
		if(cnt[i]==1)nxt[i]=i;
	}
	memset(c,0,sizeof(c));
	for(int i=n;i>=1;i--)
	{
		ll k=suf[a[i]+1]*s2[a[i]]%MOD;
		if(nxt[a[i]]+1>a[i]-1)
		{
			add(a[i],pre[a[i]]*quick_pow(s2[a[i]],MOD-2)%MOD);
			continue;
		}
		ans=(ans-k*sum(nxt[a[i]]+1,a[i]-1)%MOD*inv2)%MOD;
		add(a[i],pre[a[i]]*quick_pow(s2[a[i]],MOD-2)%MOD);
	}
	if(ans<0)ans+=MOD;
	printf("%lld\n",ans);
	return 0;
}