#include<bits/stdc++.h>
#define mo 1000000007
#define N 200005
using namespace std;
int a[N],cnt[N],n,ans;
int val0[N],val1[N],t[N];
int invval1[N],nxt[N],pre[N];
int power(int x,int y){
	int s=1;
	for (;y;y/=2,x=1ll*x*x%mo)
		if (y&1) s=1ll*s*x%mo;
	return s; 
}
void add(int x,int y){
	for (;x<=n;x+=x&(-x)) t[x]=(t[x]+y)%mo;
}
int ask(int x){
	int s=0;
	for (;x;x-=x&(-x)) s=(s+t[x])%mo;
	return s;
}
int main(){
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
		scanf("%d",&a[i]),cnt[a[i]]++;
	for (int i=n-1;i;i--) cnt[i]+=cnt[i+1]-1;
	for (int i=n;i;i--)
		if (cnt[i]<=0) return puts("0"),0;
	val0[0]=val1[0]=1;
	for (int i=1;i<=n;i++){
		val0[i]=1ll*val0[i-1]*cnt[i]%mo;
		val1[i]=1ll*val1[i-1]*max(cnt[i]-1,1)%mo;
	}
	for (int i=1;i<=n;i++){
		val1[i]=1ll*val1[i]*power(val0[i],mo-2)%mo;
		invval1[i]=power(val1[i],mo-2);
	}
	nxt[n]=n;
	for (int i=n-1;i;i--)
		nxt[i]=(cnt[i+1]==1?i:nxt[i+1]);
	for (int i=n;i;i--){
		int tmp=(ask(nxt[a[i]])+mo-ask(a[i]-1))%mo;
		ans=(ans+1ll*tmp*invval1[a[i]]%mo)%mo;
		add(a[i],val1[a[i]]);
	}
	memset(t,0,sizeof(t));
	pre[1]=1;
	for (int i=2;i<=n;i++)
		pre[i]=(cnt[i]==1?i:pre[i-1]);
	for (int i=n;i;i--){
		int tmp=(ask(a[i]-1)+mo-ask(pre[a[i]]-1))%mo;
		ans=(ans+mo-1ll*tmp*val1[a[i]]%mo)%mo;
		add(a[i],invval1[a[i]]);
	}
	ans=1ll*ans*power(2,mo-2)%mo;
	memset(t,0,sizeof(t));
	for (int i=n;i;i--){
		ans=(ans+ask(a[i]-1))%mo;
		add(a[i],1);
	}
	printf("%d",1ll*ans*val0[n]%mo);
}