#include<bits/stdc++.h>
using namespace std;
const int p=1000000007;
int inv2,n,a[200010],cnt[200010],c[200010],c1[200010],o[200010],g[200010],ans;
int D[200010],invd[200010];
int read()
{
	int x=0;
	char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9') {
		x=(x<<3)+(x<<1)+ch-'0';
		ch=getchar();
	}
	return x;
}
void add(int x,int y) {for(;x<=n;x+=x&-x) (c[x]+=y)%=p;}
int ask(int x) {int y=0;for(;x;x-=x&-x) (y+=c[x])%=p; return y;}
void add1(int x) {for(;x<=n;x+=x&-x) ++c1[x];}
int ask1(int x) {int y=0;for(;x;x-=x&-x) y+=c1[x]; return y;}
int poww(int a,int k)
{
	int ans=1;
	for(;k;k>>=1)
	{
		if(k&1) ans=1ll*ans*a%p;
		a=1ll*a*a%p;
	}
	return ans;
}
int main()
{
	n=read(); inv2=(p+1)/2;
	for(int i=1;i<=n;++i) cnt[a[i]=read()]++;
	for(int i=n-1;i>=1;--i) cnt[i]+=cnt[i+1];
	bool flag=1; int s=1;
	for(int i=1;i<=n&&flag;++i) {
		if(cnt[i]-(n-i)<=0) flag=0;
		else s=1ll*s*(cnt[i]-(n-i))%p;
	}
	if(flag==0) {printf("0"); return 0;}
	D[0]=1;
	for(int i=1;i<=n;++i)
	{
		o[i]=o[i-1]; D[i]=D[i-1];
		if(cnt[i]-(n-i)==1) {o[i]++; g[o[i]]=i;}
		else{
			D[i]=1ll*D[i]*(cnt[i]-(n-i)-1)%p*poww(cnt[i]-(n-i),p-2)%p;
		}
		invd[i]=poww(D[i],p-2);
	}
	for(int i=1;i<=n;++i)
	{
		ans=(ans+1ll*(ask(a[i])-ask(g[o[a[i]]]-1)+p)*D[a[i]]%p*s%p*inv2)%p;
		add(a[i],invd[a[i]]);
	}
	for(int i=1;i<=n;++i) c[i]=0;
	for(int i=n;i>=1;--i)
	{
		ans=(ans-1ll*(ask(a[i]-1)-ask(g[o[a[i]]]-1)+p)*D[a[i]]%p*s%p*inv2%p+p)%p;
		ans=(ans+1ll*ask1(a[i]-1)*s)%p;
		add(a[i],invd[a[i]]);
		add1(a[i]);
	}
	cout<<ans;
	return 0;
}