#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define w a[i]
typedef long long LL;
inline int gi(){
  int x=0,f=1;char ch=getchar();
  while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
  while(isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
  return x*f;
}
template<typename T>inline bool Max(T &a,T b){return a<b?a=b,1:0;}
template<typename T>inline bool Min(T &a,T b){return a>b?a=b,1:0;}
const int N=2e5 + 7,mod=1e9 + 7;
const LL inv2=500000004ll;
int n;
int a[N],cnt[N],z[N],S[N];
LL tot=1,D[N],t1[N],t2[N],ans;
LL Pow(LL a,LL b){
  LL res=1ll;
  for(;b;b>>=1,a=a*a%mod) if(b&1) res=res*a%mod;
  return res;
}
LL Inv(LL a){return Pow(a,mod-2);}
int lowbit(int x){return x&-x;}
void c1(int x,LL y){for(int i=x;i<=n;i+=lowbit(i)) t1[i]=(t1[i]+y)%mod;}
LL q1(LL x){LL res=0;for(int i=x;i;i-=lowbit(i)) res=(res+t1[i])%mod;return res;}
LL q1(int l,int r){
	if(l>r) return 0;
    return ((q1(r)-q1(l-1))%mod+mod)%mod;
}
void c2(int x,int y){for(int i=x;i<=n;i+=lowbit(i)) t2[i]+=y;}
int q2(int x){int res=0;for(int i=x;i;i-=lowbit(i)) res+=t2[i];return res;}
int q2(int l,int r){
	if(l>r) return 0;
	return q2(r)-q2(l-1);
}
void add(LL &a,LL b){ a+=b;if(a>=mod) a-=mod; }
int main(){
	n=gi();
	rep(i,1,n) ++cnt[w=gi()];
	for(int i=n-1;i;--i) cnt[i]+=cnt[i+1];
	rep(i,1,n) cnt[i]-=n-i;
	rep(i,1,n) tot=tot*cnt[i]%mod;
	if(!tot) return puts("0"),0;
    D[0]=1;
    rep(i,1,n){//D表示每个数字计算结果的前缀积 (和位置无关)
    	LL x=1ll*(cnt[i]-1)*Inv(cnt[i])%mod;
    	z[i]=z[i-1],D[i]=D[i-1];
    	if(!x) S[++z[i]]=i;
    	else D[i]=D[i]*x%mod;
    }
    rep(i,1,n){
    	(ans+=(q1(1,w)-(z[w]==1?0:q1(1,S[z[w]])))*D[w]%mod*inv2%mod*tot%mod)%=mod;
    	c1(w,Inv(D[w]));
    }
    memset(t1,0,sizeof t1);
    rep(i,1,n){
    	ans-=(q1(w+1,n)-(!S[z[w]+1]?0:q1(S[z[w]+1],n)))*Inv(D[w])%mod*inv2%mod*tot%mod;
    	add(ans,tot*q2(w+1,n)%mod);
    	c1(w,D[w]);c2(w,1);
    }
    printf("%lld\n",(ans%mod+mod)%mod);
	return 0;
}