#include<bits/stdc++.h>
#define llong long long
using namespace std;

inline int read()
{
	int x = 0,f = 1; char ch = getchar();
	for(;!isdigit(ch);ch=getchar()) {if(ch=='-') f = -1;}
	for(;!isdigit(ch);ch=getchar()) {x = x*10+ch-48;}
	return x*f;
}

const int N = 2e5;
const int P = 1e9+7;
const llong INV2 = 5e8+4;
int a[N+3];
int cnt[N+3];
llong d[N+3];
int r[N+3];
int num0[N+3];
int n; llong ans,tot;

llong quickpow(llong x,llong y)
{
	llong cur = x,ret = 1ll;
	for(int i=0; y; i++)
	{
		if(y&(1ll<<i)) {y-=(1ll<<i); ret = ret*cur%P;}
		cur = cur*cur%P;
	}
	return ret;
}
llong mulinv(llong x) {return quickpow(x,P-2);}

struct BITree
{
	llong bit[N+3];
	void add(int u,llong x) {while(u<=n) {bit[u] = (bit[u]+x)%P; u+=(u&(-u));}}
	llong query(int u) {llong ret = 0ll; while(u) {ret = (ret+bit[u])%P; u-=(u&(-u));} return ret;}
	void clear() {for(int i=1; i<=n; i++) bit[i] = 0ll;}
} bit1,bit2;


int main()
{
	scanf("%d",&n);
	for(int i=1; i<=n; i++) scanf("%lld",&a[i]);
	for(int i=1; i<=n; i++) cnt[a[i]]++;
	for(int i=n-1; i>=1; i--) cnt[i] += cnt[i+1];
	for(int i=1; i<=n; i++) cnt[i] -= (n-i);
	tot = 1ll; for(int i=1; i<=n; i++) tot = tot*cnt[i]%P;
	if(tot==0) {puts("0"); return 0;}
	d[0] = 1ll;
	for(int i=1; i<=n; i++)
	{
		llong tmp = (bit1.query(n)-bit1.query(a[i])+P)*tot%P; ans = (ans+tmp)%P;
		bit1.add(a[i],1);
	}
	bit1.clear();
	for(int i=1; i<=n; i++)
	{
		llong tmp = (cnt[i]-1)*mulinv(cnt[i])%P;
		if(tmp) {d[i] = d[i-1]*tmp%P; num0[i] = num0[i-1];}
		else {d[i] = d[i-1]; num0[i] = num0[i-1]+1; r[num0[i-1]] = i-1;}
	}
	r[num0[n]] = n;
	for(int i=n; i>=1; i--)
	{
		llong tmp = (bit1.query(r[num0[a[i]]])-bit1.query(a[i]-1)+P)*mulinv(d[a[i]])%P*INV2%P*tot%P;
		ans = (ans+tmp)%P;
		bit1.add(a[i],d[a[i]]);
	}
	for(int i=n; i>=1; i--) {bit1.add(a[i],P-d[a[i]]);}
	for(int i=1; i<=n; i++)
	{
		llong tmp2 = (bit2.query(r[num0[a[i]]])-bit2.query(a[i])+P)*mulinv(d[a[i]])%P*INV2%P*tot%P;
		ans = (ans-tmp2+P)%P;
		bit2.add(a[i],d[a[i]]);
	}
	for(int i=1; i<=n; i++)
	{
		bit2.add(a[i],P-d[a[i]]);
	}
	printf("%lld\n",ans);
	return 0;
}