#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200005,p=1000000007,INV2=(p+1)/2;
int read(){
	int f=1,g=0;
	char ch=getchar();
	for (;!isdigit(ch);ch=getchar()) if (ch=='-') f=-1;
	for (;isdigit(ch);ch=getchar()) g=g*10+ch-'0';
	return f*g;
}
int qpow(int x,int k){
	int t=1;
	for (;k;k>>=1){
		if (k&1) t=(ll)t*x%p;
		x=(ll)x*x%p;
	}
	return t;
}
int n,a[N],b[N],las[N],h[N],f[N],g[N],invf[N],invg[N],ans;
void check(int &x,int y){if ((x+=y)>=p) x-=p;}
struct BIT{
	int f[N];
	void clear(){memset(f,0,sizeof(f));}
	int lowbit(int x){return x&(-x);}
	void add(int x,int val){for (;x<=n;x+=lowbit(x)) check(f[x],val);}
	int que(int x){
		int t=0;
		for (;x;x-=lowbit(x)) check(t,f[x]);
		return t;
	}
}s,cnt;
int main(){
	n=read();
	for (int i=1;i<=n;i++) a[i]=read(),h[a[i]]++;
	for (int i=n;i;i--) h[i]+=h[i+1];
	f[0]=g[0]=1;
	for (int i=1;i<=n;i++){
		b[i]=h[i]-(n-i);
		f[i]=(ll)f[i-1]*b[i]%p;
		las[i]=(b[i]==1) ? i : las[i-1];
		g[i]=(ll)g[i-1]*max(1,b[i]-1)%p;
	}
	if (!f[n]){puts("0");return 0;}
	invf[n]=qpow(f[n],p-2);
	invg[n]=qpow(g[n],p-2);
	for (int i=n;i;i--) invf[i-1]=(ll)invf[i]*b[i]%p,invg[i-1]=(ll)invg[i]*max(b[i]-1,1)%p;
	for (int i=1;i<=n;i++){
		int t=(ll)f[n]*invf[a[i]]%p*g[a[i]]%p*(s.que(a[i])-s.que(las[a[i]])+p)%p*INV2%p;
		check(ans,t);
		s.add(a[i],(ll)f[a[i]]*invg[a[i]]%p);
	}
	s.clear();
	for (int i=n;i;i--){
		int t=(ll)f[n]*cnt.que(a[i]-1)%p;
		if (las[a[i]]!=a[i]) check(t,p-(ll)f[n]*invf[a[i]]%p*g[a[i]]%p*(s.que(a[i]-1)-s.que(las[a[i]])+p)%p*INV2%p);
		check(ans,t);
		s.add(a[i],(ll)f[a[i]]*invg[a[i]]%p);cnt.add(a[i],1);
	}
	printf("%d\n",ans);
	return 0;
}