#include <bits/stdc++.h>
#define Maxn 400007
#define modp 1000000007
using namespace std;
int n;
int a[Maxn],b[Maxn],c[Maxn];
int t[Maxn],s[Maxn];
int ans=0;
int power(int a,int b)
{
	int res=1,now=a,left=b;
	while (left>0)
	{
		if (left%2==1) res=(1LL*res*now)%modp;
		left/=2;
		now=(1LL*now*now)%modp;
	}
	return res;
}
void add(int pos,int val)
{
	for (int k=pos;k<=n;k+=k&(-k))
		s[k]=(s[k]+val)%modp;
}
int query(int pos)
{
	if (pos==0) return 0;
	int res=0;
	for (int k=pos;k;k-=k&(-k))
		res=(res+s[k])%modp;
	return res;
}
int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		++c[a[i]];
	}
	for (int i=n-1;i;i--)
		c[i]+=c[i+1]-1;
	for (int i=1;i<=n;i++)
		if (c[i]<=0)
		{
			printf("%d\n",0);
			return 0;
		}
	int sum=1;
	b[0]=1;
	for (int i=1;i<=n;i++)
	{
		sum=(1LL*sum*c[i])%modp;
		if (c[i]==1) b[i]=b[i-1]; else b[i]=(1LL*b[i-1]*(c[i]-1))%modp;
		b[i]=(1LL*b[i]*power(c[i],modp-2))%modp;
	}
	memset(s,0,sizeof(s));
	t[n]=n;
	for (int i=n-1;i;i--)
		if (c[i+1]>1) t[i]=t[i+1]; else t[i]=i;
	for (int i=n;i;i--)
	{
		int del=(query(t[a[i]])-query(a[i]-1)+modp)%modp;
		ans=(ans+1LL*del*power(b[a[i]],modp-2))%modp;
		add(a[i],b[a[i]]);
	}
	memset(s,0,sizeof(s));
	t[1]=1;
	for (int i=2;i<=n;i++)
		if (c[i]>1) t[i]=t[i-1]; else t[i]=i;
	for (int i=n;i;i--)
	{
		int del=(query(a[i]-1)-query(t[a[i]]-1)+modp)%modp;
		ans=(ans+modp-(1LL*del*b[a[i]])%modp)%modp;
		add(a[i],power(b[a[i]],modp-2));
	}
	ans=(1LL*ans*power(2,modp-2))%modp;
	memset(s,0,sizeof(s));
	for (int i=1;i<=n;i++)
	{
		ans=(ans+i+modp-1-query(a[i]))%modp;
		add(a[i],1);
	}
	printf("%lld\n",(1LL*ans*sum)%modp);
	return 0;
}
