#include<bits/stdc++.h>
#define FILE "belief"
#define RG register
#define il inline
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int N=2e5+5;
il ll read(){
	RG ll data=0,w=1;RG char ch=getchar();
	while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
	if(ch=='-')w=-1,ch=getchar();
	while(ch<='9'&&ch>='0')data=data*10+ch-48,ch=getchar();
	return data*w;
}
il void file(){
	freopen(FILE".in","r",stdin);
	freopen(FILE".out","w",stdout);
}
il void upd(int &a,int b){a+=b;if(a>=mod)a-=mod;}
il void dec(int &a,int b){if(b)upd(a,mod-b);}
struct data{int sum,cnt;}tr[N<<2],tmp;int tag[N<<2];
data operator +(data a,data b){
	upd(a.sum,b.sum);upd(a.cnt,b.cnt);return a;
}
int n,a[N],cnt[N],prod,i,x,fac,d[N],ans,rev2;
int cntt,head[N],nxt[N],to[N];
int poww(int a,int b){
	RG int ret=1;
	for(;b;b>>=1,a=1ll*a*a%mod)
		if(b&1)ret=1ll*ret*a%mod;
	return ret;
}
#define ls (i<<1)
#define rs (i<<1|1)
#define mid ((l+r)>>1)
il void pushdown(int i,int s){
	if(tag[i]==1)return;
	if(!s){
		tag[ls]=1ll*tag[ls]*tag[i]%mod;
		tag[rs]=1ll*tag[rs]*tag[i]%mod;
	}
	tr[i].sum=1ll*tr[i].sum*tag[i]%mod;tag[i]=1;
}
data query(int i,int l,int r,int x,int y){
	if(l==x&&r==y)return tr[i];
	pushdown(ls,l==mid);pushdown(rs,(mid+1)==r);RG data ret=(data){0,0};
	if(x<=mid)ret=ret+query(ls,l,mid,x,min(mid,y));
	if(mid<y)ret=ret+query(rs,mid+1,r,max(x,mid+1),y);
	return ret;
}
void modify(int i,int l,int r,int p,int v){
	if(l==r){tr[i].cnt=1;tr[i].sum=v;return;}
	pushdown(ls,l==mid);pushdown(rs,(mid+1)==r);
	if(p<=mid)modify(ls,l,mid,p,v);else modify(rs,mid+1,r,p,v);
	tr[i]=tr[ls]+tr[rs];
}
int main()
{
	//file();
	n=read();
	for(RG int i=1;i<=n;i++){
		a[i]=read();cnt[a[i]]++;
		to[++cntt]=i;nxt[cntt]=head[a[i]];head[a[i]]=cntt;
	}
	for(RG int i=n;i;i--)cnt[i]+=cnt[i+1];
	RG int prod=1;
	for(RG int i=1;i<=n;i++)prod=1ll*prod*(cnt[i]-(n-i))%mod;
	for(RG int i=1;i<=(n<<2);i++)tag[i]=1;rev2=poww(2,mod-2);
	for(RG int x=n;x;x--){
		d[0]=0;for(RG int i=head[x];i;i=nxt[i])d[++d[0]]=to[i];
		fac=1ll*(cnt[x]-1-(n-x))*poww(cnt[x]-(n-x),mod-2)%mod;
		for(RG int i=1;i<=d[0];i++){
			tmp=query(1,1,n,d[i],n);
			upd(ans,1ll*tmp.sum*rev2%mod);
			tmp=query(1,1,n,1,d[i]);
			upd(ans,1ll*tmp.cnt*prod%mod);dec(ans,1ll*tmp.sum*rev2%mod);
		}
		upd(ans,1ll*d[0]*(d[0]-1)/2%mod*prod%mod*rev2%mod);
		for(RG int i=1;i<=d[0];i++)modify(1,1,n,d[i],prod);
		tag[1]=1ll*tag[1]*fac%mod;pushdown(1,n==1);
	}
	printf("%d\n",ans);
	return 0;
}
