#include<bits/stdc++.h>
const int N=2e5+5,mo=1e9+7;
int n,a[N],b1[N],b2[N],f1[N],f2[N],f22[N],all=1,i,ans,inv[N];
struct pii{
	int x,y;
	inline pii(int _x=0,int _y=0):x(_x),y(_y){}
	inline pii operator+(const pii&rhs)const{return pii(1ll*x*rhs.x%mo,(1ll*y*rhs.x+rhs.y)%mo);}
};
int bi[N];
inline void add(int x){for(;x<=n;x+=x&-x)bi[x]++;}
inline int ask(int x){int ans=0;for(;x;x-=x&-x)ans+=bi[x];return ans;}
struct node{
	int lb,rb,md;
	int pi,s1,s2;
}t[N<<2];
void build(int i,int l,int r){
	t[i].lb=l;t[i].rb=r;t[i].md=l+r>>1;
	if(l==r){
		t[i].pi=b2[l];
		return;
	}
	build(i<<1,l,t[i].md);build(i<<1|1,t[i].md+1,r);
	t[i].pi=1ll*t[i<<1].pi*t[i<<1|1].pi%mo;
}
pii ask1(int i,int k){
	if(t[i].rb<=k)return pii(t[i].pi,t[i].s1);
	if(k<=t[i].md)return ask1(i<<1,k);else return pii(t[i<<1].pi,t[i<<1].s1)+ask1(i<<1|1,k);
}
pii ask2(int i,int k){
	if(k<=t[i].lb)return pii(t[i].pi,t[i].s2);
	if(k<=t[i].md)return pii(t[i<<1|1].pi,t[i<<1|1].s2)+ask2(i<<1,k);else return ask2(i<<1|1,k);
}
void mdy(int i,int k){
	if(t[i].lb==k && t[i].rb==k){
		t[i].s1=(t[i].s1+f2[k])%mo;
		t[i].s2=(t[i].s2+b2[k])%mo;
		return;
	}
	if(k<=t[i].md)mdy(i<<1,k);else mdy(i<<1|1,k);
	t[i].s1=(1ll*t[i<<1].s1*t[i<<1|1].pi+t[i<<1|1].s1)%mo;
	t[i].s2=(1ll*t[i<<1|1].s2*t[i<<1].pi+t[i<<1].s2)%mo;
}
int main(){
	for(i=1;i<N;++i)inv[i]=i==1?1:1ll*(mo-mo/i)*inv[mo%i]%mo;
	scanf("%d",&n);
	for(i=1;i<=n;++i)scanf("%d",a+i),++b1[a[i]];
	b1[n+1]=1;for(i=n;i;--i)ans=(ans+1ll*b1[i]*(b1[i]-1)/2)%mo,b1[i]+=b1[i+1]-1,all=1ll*all*b1[i]%mo;
	if(!all)return puts("0"),0;
	ans=1ll*inv[2]*ans%mo;
	for(i=1;i<=n;++i){
		b2[i]=1ll*inv[b1[i]]*(b1[i]-1)%mo;
		f1[i]=(1ll*b2[i]*f1[i-1]+inv[b1[i]])%mo;
		f2[i]=(1ll*inv[b1[i]]*f1[i-1]+(b1[i]<3?0:1ll*inv[b1[i]]*(b1[i]-2)%mo)*f2[i-1])%mo;
	}
	build(1,1,n);
	for(i=1;i<=n;++i){
		if(a[i]>1)ans=(ans+1ll*ask1(1,a[i]-1).y*b2[a[i]])%mo;
		if(a[i]<n)ans=(ans+1ll*mo+(i-1-ask(a[i]))-1ll*f2[a[i]]*ask2(1,a[i]+1).y%mo)%mo;
		mdy(1,a[i]);add(a[i]);
	}
	ans=1ll*ans*all%mo;
	printf("%d\n",ans);
	return 0;
}