#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
#define x first
#define y second
#define mp make_pair
#define pb push_back
template <typename TYPE> inline void chkmax(TYPE &x,TYPE y){x<y?x=y:0;}
template <typename TYPE> inline void chkmin(TYPE &x,TYPE y){y<x?x=y:0;}
template <typename TYPE> void readint(TYPE &x)
{
    x=0;int f=1;char c;
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())x=x*10+c-'0';
    x*=f;
}
const int MAXN=200005,MOD=1000000007,INV2=(MOD+1)>>1;
int qmi(int x,int y)
{
	int ans=1;
	for(;y;y>>=1,x=1ll*x*x%MOD)
		if(y&1)ans=1ll*ans*x%MOD;
	return ans;
}
inline int dmy(int x){return x>=MOD?x-MOD:x;}

int n,a[MAXN],b[MAXN],p[MAXN],las[MAXN],nxt[MAXN],invp[MAXN];
struct Fenwick
{
	int c[MAXN];
	void add(int x,int d){for(;x<=n;x+=(x&-x))c[x]=dmy(c[x]+d);}
	int query(int x){int s=0;for(;x;x-=(x&-x))s=dmy(s+c[x]);return s;}
}c0,c1,c2;

int main()
{
	#ifndef ONLINE_JUDGE
//	freopen("code.in","r",stdin);
//	freopen("code.out","w",stdout);
	#endif
	int sum=INV2,ans=0;
	readint(n);
	for(int i=1;i<=n;++i)readint(b[i]),++a[b[i]];
	for(int i=n;i;--i)a[i]+=a[i+1];
	p[0]=1;
	for(int i=1;i<=n;++i)
	{
		a[i]-=(n-i);
		if(a[i]<=0)return 0*printf("0\n");
		if(p[i-1])p[i]=1ll*p[i-1]*(a[i]-1)%MOD*qmi(a[i],MOD-2)%MOD;
		else p[i]=1ll*(a[i]-1)*qmi(a[i],MOD-2)%MOD;
		if(a[i]==1)las[i]=i;
		else las[i]=las[i-1];
		invp[i]=qmi(p[i],MOD-2);
		sum=1ll*sum*a[i]%MOD;
	}
	nxt[n+1]=n+1;
	for(int i=n;i;--i)
		if(a[i]==1)nxt[i]=i;
		else nxt[i]=nxt[i+1];
//for(int i=1;i<=n;++i)cerr<<a[i]<<" "<<p[i]<<" "<<invp[i]<<" "<<las[i]<<endl;
	for(int i=1;i<=n;++i)
	{
		ans=(ans+1ll*(c0.query(b[i])-c0.query(las[b[i]])+MOD)*sum%MOD*p[b[i]])%MOD;
		ans=(ans+1ll*(c2.query(b[i])-c2.query(nxt[b[i]]-1)+MOD)*sum%MOD*invp[b[i]])%MOD;
		ans=(ans+2ll*(c1.query(n)-c1.query(b[i])+MOD)%MOD*sum)%MOD;
		c0.add(b[i],invp[b[i]]);
		c1.add(b[i],1);
		c2.add(b[i],p[b[i]]);
	}
	printf("%d\n",ans);
	return 0;
}