#include<bits/stdc++.h>
using namespace std;
template<class T>void gi(T &x){
	int f;char c;
	for(f=1,c=getchar();c<'0'||c>'9';c=getchar())if(c=='-')f=-1;
	for(x=0;c<='9'&&c>='0';c=getchar())x=x*10+(c&15);x*=f;
}

const int N=2e5+10,mod=1e9+7;
inline int qm(int x,int k){
	int sum=1;
	while(k){
		if(k&1)sum=1ll*sum*x%mod;
		x=1ll*x*x%mod;k>>=1;
	}
	return sum;
}
int n,a[N],c[N],v0[N],R[N],tr[N],S;
inline void add(int x,int t){
	for(int i=x;i<=n;i+=(i&(-i)))tr[i]=(tr[i]+t)%mod;
}
inline int qry(int x){
	int ret=0;
	for(int i=x;i>=1;i-=(i&(-i)))ret=(ret+tr[i])%mod;
	return ret;
}
int main(){
  cin>>n;
  for(int i=1;i<=n;i++)gi(a[i]),c[a[i]]++;
  for(int i=n-1;i>=1;i--)c[i]+=c[i+1]-1;
  for(int i=1;i<=n;i++)if(c[i]<=0)return puts("0"),0;
  v0[0]=S=1;
  for(int i=1;i<=n;i++){
	  v0[i]=1ll*v0[i-1]*(c[i]>1?c[i]-1:1)%mod*qm(c[i],mod-2)%mod;
	  S=1ll*S*c[i]%mod;
  }
  R[n]=n;
  for(int i=n-1;i>=1;i--)R[i]=c[i+1]>1?R[i+1]:i;
  int ans=0,t;
  //A[i]<=A[j]
  for(int i=n;i>=1;i--){
	  t=(qry(R[a[i]])-qry(a[i]-1)+mod)%mod;
	  ans=(ans+1ll*t*qm(v0[a[i]],mod-2))%mod;
	  add(a[i],v0[a[i]]);
  }
  //A[i]>A[j]
  R[1]=1;
  memset(tr,0,sizeof(tr));
  for(int i=2;i<=n;i++)R[i]=c[i]>1?R[i-1]:i;
  for(int i=n;i>=1;i--){
	  t=(qry(a[i]-1)-qry(R[a[i]]-1)+mod)%mod;
	  ans=(ans-1ll*t*v0[a[i]]%mod+mod)%mod;
	  add(a[i],qm(v0[a[i]],mod-2));
  }
  ans=1ll*ans*qm(2,mod-2)%mod;
  memset(tr,0,sizeof(tr));
  for(int i=1;i<=n;i++){
	  ans=(1ll*ans+i-1-qry(a[i])+mod)%mod;
	  add(a[i],1);
  }
  ans=1ll*ans*S%mod;
  cout<<ans<<endl;
  return 0;
}
