#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
typedef long long LL;
const int N=200005;
const int MOD=1e9+7;
int add (int x,int y)   {x=x+y;return x>=MOD?x-MOD:x;}
int mul (int x,int y)   {return (LL)x*y%MOD;}
int dec (int x,int y)   {x=x-y;return x<0?x+MOD:x;}
int Pow (int x,int y)
{
	if (y==0) return 1;
	if (y==1) return x;
	int lalal=Pow(x,y>>1);
	lalal=mul(lalal,lalal);
	if (y&1) lalal=mul(lalal,x);
	return lalal;
}
int n;
int a[N];
int num[N];
int D[N],cnt[N];
int suf[N],pre[N];
int Inv (int x)	{return Pow(x,MOD-2);}
int f[2][N];
int lb (int x)	{return x&(-x);}
void modify (int op,int x,int c)	{while (x<=n)	{f[op][x]=add(f[op][x],c);x+=lb(x);}}
int query (int op,int x)	{int lalal=0;while (x>=1)	{lalal=add(lalal,f[op][x]);x-=lb(x);}return lalal;}
int main()
{
	scanf("%d",&n);
	for (int u=1;u<=n;u++) scanf("%d",&a[u]),num[a[u]]++;
	for (int u=n-1;u>=1;u--) num[u]+=num[u+1];
	int S=1;D[0]=1;
	for (int u=1;u<=n;u++)
	{
		cnt[u]=num[u]-(n-u);S=mul(S,cnt[u]);
		if (cnt[u]<=0)	{printf("0\n");return 0;}
		D[u]=D[u-1];
		if (cnt[u]>1)	{D[u]=mul(D[u],mul(cnt[u]-1,Inv(cnt[u])));pre[u]=pre[u-1];}
		else pre[u]=u;
	}
	//printf("%d\n",S);
	suf[n]=n;
	for (int u=n-1;u>=1;u--)
	{
		if (cnt[u]>1)
		{
			if (cnt[u+1]>1) suf[u]=suf[u+1];
			else suf[u]=u;
		}
		else	suf[u]=u;
	}
	int ans=0;
	for (int u=1;u<=n;u++)
	{
		int tmp=dec(query(0,a[u]),query(0,pre[a[u]]-1));
		tmp=mul(mul(D[a[u]],mul(tmp,S)),Inv(2));
		ans=add(ans,tmp);
		modify(0,a[u],Inv(D[a[u]]));
	}
	memset(f[0],0,sizeof(f[0]));
	for (int u=1;u<=n;u++)
	{
		int tmp1=mul(S,dec(query(1,n),query(1,a[u]))),tmp;
		
		tmp=dec(query(0,suf[a[u]]),query(0,a[u]));
		tmp=mul(mul(Inv(D[a[u]]),mul(tmp,S)),Inv(2));
		ans=add(ans,dec(tmp1,tmp));
		
		modify(0,a[u],D[a[u]]);
		modify(1,a[u],1);
	}
	printf("%d\n",ans);
	return 0;
}