#include<bits/stdc++.h>
#define debug(x) cerr<<#x<<" = "<<x
#define sp <<"  "
#define el <<endl
#define fgx cerr<<" ----------------------------------- "<<endl
#define LL long long
#define DB double
#define LDB long double
#define ULL unsigned long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
using namespace std;
inline LL read(){
	LL nm=0; bool fh=true; char cw=getchar();
	for(;!isdigit(cw);cw=getchar()) fh^=(cw=='-');
	for(;isdigit(cw);cw=getchar()) nm=nm*10+(cw-'0');
	return fh?nm:-nm;
}
#define M 200020
#define mod 1000000007
#define inv2 500000004
namespace CALC{
	inline int add(int x,int y){return (x+y>=mod)?(x+y-mod):(x+y);}
	inline int mns(int x,int y){return (x-y<0)?(x-y+mod):(x-y);}
	inline int mul(int x,int y){return (LL)x*(LL)y%mod;}
	inline void upd(int &x,int y){x=((x+y>=mod)?(x+y-mod):(x+y));}
	inline void dec(int &x,int y){x=((x-y<0)?(x-y+mod):(x-y));}
	inline int qpow(int x,int sq){int res=1;for(;sq;sq>>=1,x=mul(x,x))if(sq&1)res=mul(res,x);return res;}
}using namespace CALC;
int n,m,tmp,A[M],cnt[M],All,ans;
int las[M],c[M],iv[M],pre[M],inv_pre[M];
inline void mdf(int l,int r,int val){
	if(l>r) return;
	for(int k=l;k<=n;k+=(k&-k)) upd(c[k],val);
	for(int k=r+1;k<=n;k+=(k&-k)) dec(c[k],val);
}
inline int qry(int k,int res=0){for(;k;k-=(k&-k))upd(res,c[k]);return res;}
int main(){
	n=read(),iv[1]=iv[0]=All=1;
	for(int i=2;i<=n;i++) iv[i]=mul(mns(mod,mod/i),iv[mod%i]),assert(mul(iv[i],i)==1);
	for(int i=1;i<=n;i++) ++cnt[A[i]=read()];
	for(int i=n;i>=1;i--) cnt[i]+=cnt[i+1]; pre[0]=inv_pre[0]=1;
	for(int i=1;i<=n;i++) if((cnt[i]=cnt[i]-(n-i))<=0){puts("0");return 0;}
	for(int i=1;i<=n;i++){
		if(cnt[i]>1) pre[i]=mul(mul(pre[i-1],cnt[i]-1),iv[cnt[i]]),las[i]=las[i-1];
		else pre[i]=pre[i-1],las[i]=i; All=mul(All,cnt[i]),inv_pre[i]=qpow(pre[i],mod-2);
	}
	for(int i=n;i>=1;i--){
		upd(ans,mul(inv_pre[A[i]],qry(A[i])));
		mdf(las[A[i]]+1,A[i],mul(All,pre[A[i]]));
	} memset(c,0,sizeof(c));
	for(int i=1;i<=n;i++){
		dec(ans,mul(inv_pre[A[i]],qry(A[i])));
		mdf(las[A[i]]+1,A[i]-1,mul(All,pre[A[i]]));
	} ans=mul(ans,inv2),memset(c,0,sizeof(c)); int rem=0;
	for(int i=1;i<=n;i++) upd(rem,qry(A[i])),mdf(1,A[i]-1,1);
	upd(ans,mul(rem,All)),printf("%d\n",ans); return 0;
}