#include<iostream>
#include<cstdio>
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=200200,P=1e9+7,iv2=P+1>>1;
int n,x,S,ans;
int a[N],f[N],g[N],h[N],t[N],L[N],R[N],c[3][N];
void chk(int&x){x-=P;x+=(x>>31)&P;}
int qpw(int x,int y){int z=1;for(;y;y>>=1,x=1ll*x*x%P)if(y&1) z=1ll*z*x%P;return z;} 
void add(int k,int x,int y){ for(;x<=n;x+=x&-x) chk(c[k][x]+=y);}
int ask(int k,int x){int y=0;for(;x;x-=x&-x) chk(y+=c[k][x]); return y;}
int main(){
	//freopen("1.in","r",stdin);
	scanf("%d",&n);
	FOR(i,1,n) scanf("%d",&a[i]),f[a[i]]++;
	ROF(i,n,1) f[i]+=f[i+1];
	FOR(i,1,n)if((f[i]-=n-i)<=0) return puts("0"),0;
	S=1;g[0]=1;
	FOR(i,1,n){
		g[i]=qpw(f[i],P-2);t[i]=t[i-1]; 
		f[i]^1?g[i]=1ll*g[i]*(f[i]-1)%P:t[i]++;
		g[i]=1ll*g[i]*g[i-1]%P;
		h[i]=qpw(g[i],P-2);
		S=1ll*S*f[i]%P;
	}
	t[0]=t[n+1]=-1;
	FOR(i,1,n) L[i]=t[i]^t[i-1]?i:L[i-1];
	ROF(i,n,1) R[i]=t[i]^t[i+1]?i:R[i+1];
	FOR(i,1,n){
		x=a[i];
		chk(ans+=1ll*g[x]*(ask(0,x)-ask(0,L[x]-1)+P)%P);
		chk(ans+=P-1ll*h[x]*(ask(1,R[x])-ask(1,x)+P)%P);
		chk(ans+=(ask(2,n)-ask(2,x)+P)%P);
		add(0,x,h[x]);
		add(1,x,g[x]);
		add(2,x,2);
		//cout<<ans<<'\n';
	}
	cout<<1ll*ans*iv2%P*S%P<<'\n';
}