#include <bits/stdc++.h>
using namespace std;
const int Maxn=200005,mod=1e9+7,inv2=(mod+1)/2;
int a[Maxn],s[Maxn],pre[Maxn],f[Maxn],invf[Maxn];
struct node{
	int l,r,v,cnt;
}Tree[4*Maxn];
int ksm(int x,int k){
	int ret=1,tmp=x;
	while(k){
		if(k&1)ret=1ll*ret*tmp%mod;
		tmp=1ll*tmp*tmp%mod;k>>=1;
	}
	return ret;
}
int inv(int x){return ksm(x,mod-2);}
void PushUp(int v){
	Tree[v].v=(Tree[2*v].v+Tree[2*v+1].v)%mod;
	Tree[v].cnt=Tree[2*v].cnt+Tree[2*v+1].cnt;
}
void Build(int v,int l,int r){
	Tree[v]=(node){l,r,0,0};
	if(l==r)return;
	Build(2*v,l,(l+r)/2);
	Build(2*v+1,(l+r)/2+1,r);
}
void Modify(int v,int pos,int val){
	if(Tree[v].l==Tree[v].r){
		Tree[v].v=(Tree[v].v+val)%mod;
		Tree[v].cnt++;
		return;
	}
	if(pos<=Tree[2*v].r)Modify(2*v,pos,val);
	else Modify(2*v+1,pos,val);
	PushUp(v);
}
int Askv(int v,int l,int r){
	if(r<Tree[v].l||Tree[v].r<l)return 0;
	if(l<=Tree[v].l&&Tree[v].r<=r)return Tree[v].v;
	return (Askv(2*v,l,r)+Askv(2*v+1,l,r))%mod;
}
int Askc(int v,int l,int r){
	if(r<Tree[v].l||Tree[v].r<l)return 0;
	if(l<=Tree[v].l&&Tree[v].r<=r)return Tree[v].cnt;
	return Askc(2*v,l,r)+Askc(2*v+1,l,r);
}
int main(){
	int n,g=1,ans=0;scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	for(int i=1;i<=n;i++)s[a[i]]++;
	for(int i=n;i>=1;i--)s[i]+=s[i+1];
	for(int i=1;i<=n;i++)s[i]-=n-i;
	for(int i=1;i<=n;i++){
		int cur=1ll*(s[i]-1)*inv(s[i])%mod;
		if(!cur)pre[i]=i;
		else pre[i]=pre[i-1];
		f[i]=1ll*(i==1?1:f[i-1])*max(cur,1)%mod;
		invf[i]=inv(f[i]);
	}
	for(int i=n;i>=1;i--)g=1ll*g*s[i]%mod;
	Build(1,1,n);
	for(int i=1;i<=n;i++){
		ans=(ans+1ll*g*inv2%mod*Askv(1,pre[a[i]]+1,a[i])%mod*f[a[i]])%mod;
		Modify(1,a[i],invf[a[i]]);
	}
	Build(1,1,n);
	for(int i=n;i>=1;i--){
		ans=(ans+1ll*g*Askc(1,1,a[i]-1)-1ll*g*inv2%mod*Askv(1,pre[a[i]]+1,a[i]-1)%mod*f[a[i]])%mod;
		Modify(1,a[i],invf[a[i]]);
	}
	cout<<(ans+mod)%mod<<"\n";
	return 0;
}