#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define SZ(x) ((int)x.size())
#define L(i,u) for (register int i=head[u]; i; i=nxt[i])
#define rep(i,a,b) for (register int i=(a); i<=(b); i++)
#define per(i,a,b) for (register int i=(a); i>=(b); i--)
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> Pii;
typedef vector<int> Vi;
template<class T> inline void read(T &x){
	x=0; char c=getchar(); int f=1;
	while (!isdigit(c)) {if (c=='-') f=-1; c=getchar();}
	while (isdigit(c)) {x=x*10+c-'0'; c=getchar();} x*=f;
}
template<class T> inline void umin(T &x, T y){x=x<y?x:y;}
template<class T> inline void umax(T &x, T y){x=x>y?x:y;}
inline ui R() {
	static ui seed=416;
	return seed^=seed>>5,seed^=seed<<17,seed^=seed>>13;
}
const int N = 233333,mo=1e9+7,inv2=(mo+1)/2;
int power(int a, int n){
	int res=1;
	while(n){
		if(n&1)res=1LL*res*a%mo;a=1LL*a*a%mo;n>>=1;
	}
	return res;
}
void add(int &x,int y){x=(x+y)%mo;}
void sub(int &x,int y){x=(x-y+mo)%mo;}
int n,a[N],v[N],pre[N],qz[N],ans,b[N],val[N],cnt[N],res;
void modify(int *v,int p, int x){while(p<=n)add(v[p],x),p+=p&-p;}
int qry(int *v,int p){int r=0;while(p>0)add(r,v[p]),p-=p&-p;return r;}
int main() {
	read(n);rep(i,1,n)read(a[i]),v[a[i]]++;
	per(i,n,1)v[i]+=v[i+1];
	rep(i,1,n)v[i]-=n-i;
	rep(i,1,n)if(v[i]<=0){puts("0");return 0;}
	ans=1;rep(i,1,n)ans=1LL*ans*v[i]%mo;
	for(int i=1,j=0;i<=n;i++,j=v[i]==1?i:j)pre[i]=j;
	rep(i,1,n)b[i]=1LL*(v[i]-1)*power(v[i],mo-2)%mo;
	rep(i,1,n){
		if(b[i])qz[i]=1LL*b[i]*qz[i-1]%mo;else qz[i]=1;
	}
	
//	rep(i,1,n)printf("%d ",b[i]);puts("");
	
	rep(i,1,n){
		add(res,1LL*ans*qz[a[i]]%mo*(qry(val,a[i])-qry(val,pre[a[i]]-1)+mo)%mo*inv2%mo);
		modify(val,a[i],power(qz[a[i]],mo-2));
	}
	memset(val,0,sizeof(val));
	per(i,n,1){
		add(res,1LL*ans*(qry(cnt,a[i]-1))%mo);
		if(pre[a[i]]<=a[i]-1){
			sub(res,1LL*ans*qz[a[i]]%mo*(qry(val,a[i]-1)-qry(val,pre[a[i]]-1)+mo)%mo*inv2%mo);
		}
		modify(val,a[i],power(qz[a[i]],mo-2));
		modify(cnt,a[i],1);
	}
	cout<<(res%mo+mo)%mo;
	return 0;
}
