#include <bits/stdc++.h>
#define pb push_back
#define cmin(a,b) (a>b?a=b:a)
#define cmax(a,b) (a<b?a=b:a)
#define lop(i,s,t) for(int i=s;i<(t);++i)
#define rep(i,s,t) for(int i=s;i<=(t);++i)
#define dec(i,s,t) for(int i=s;i>=(t);--i)
#define fore(i,v) for(int i=g[v],d=es[i].d;i;i=es[i].nxt,d=es[i].d)
using namespace std;

typedef long long ll;

const int N=2e5+50,P=1e9+7;

int mul(int a,int b){ return 1ll*a*b%P; }
int mul(int a,int b,int c){ return mul(a,mul(b,c)); }
int add(int a,int b){ a+=b; return a>=P?a-P:a; }
int sub(int a,int b){ a-=b; return a<0?a+P:a; }
int power(int a,int k){
	int res=1;
	for(;k;k>>=1,a=mul(a,a)){
		if(k&1){
			res=mul(res,a);
		}
	}
	return res;
}
int inverse(int x){ return power(x,P-2); }

int n,a[N],g[N],cnt[N],ans,L[N],R[N];
struct BinaryIndexedTree{
	int c[N],res;
	void update(int p,int k){
		for(;p<=n;p+=p&-p)c[p]=add(c[p],k);
	}
	int query(int p){
		for(res=0;p>=1;p-=p&-p)res=add(res,c[p]); 
		return res;
	}
	void clear(){
		memset(c,0,sizeof(c)); 
	}
} trG,trC;

int main(int argc,char *argv[]){
#ifdef CURIOUSCAT
	freopen("dat.in","r",stdin);
//	freopen("my.out","w",stdout);
#endif
	cin>>n;
	rep(i,1,n){
		cin>>a[i]; 
		++cnt[a[i]];
	}
	dec(i,n-1,1)cnt[i]+=cnt[i+1];
	int prod=1;
	rep(i,1,n){
		cnt[i]-=n-i;
		if(cnt[i]<=0){
			puts("0");
			return 0;
		}
		prod=mul(prod,cnt[i]);
		if(i==1||cnt[i]==1){
			L[i]=i;
			g[i]=1;
		}else {
			L[i]=L[i-1];
			g[i]=mul(cnt[i]-1,inverse(cnt[i]));
			g[i]=mul(g[i-1],g[i]);
		}
	}
	dec(i,n,1){
		if(i==n||cnt[i]==1||cnt[i+1]==1)R[i]=i;
		else R[i]=R[i+1];
	}
	rep(i,1,n){
		int up=mul(g[a[i]],sub(trG.query(a[i]),trG.query(L[a[i]]-1)));	
		ans=add(ans,mul(prod,up,inverse(2)));
		trG.update(a[i],inverse(g[a[i]]));	
	}
	trG.clear(); 
	rep(i,1,n){
		int tot=mul(prod,sub(trC.query(n),trC.query(a[i])));
		int unl=mul(prod,mul(inverse(g[a[i]]),sub(trG.query(R[a[i]]),trG.query(a[i]))),inverse(2));
		ans=add(ans,sub(tot,unl));
		trG.update(a[i],g[a[i]]);
		trC.update(a[i],1);
	}
	printf("%d\n", ans);
	return 0;
}