#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 100000000
#define mod 1000000007
#define fi first
#define sc second
#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())
struct seg_mul{
	ll seg[(1<<19)],lazy[(1<<19)];
	void init(){
		rep(i,(1<<19)){
			seg[i] = 0;
			lazy[i] = 1;
		}
	}
	void ev(int k){
		lazy[2*k+1] = lazy[2*k+1]*lazy[k]%mod;
		lazy[2*k+2] = lazy[2*k+2]*lazy[k]%mod;
		seg[2*k+1] = seg[2*k+1]*lazy[k]%mod;
		seg[2*k+2] = seg[2*k+2]*lazy[k]%mod;
		lazy[k] = 1;
	}
	ll query(int a,int b,int k,int l,int r){
		if(r<a || b<l) return 0;
		if(a<=l && r<=b){
			return seg[k];
		}
		if(lazy[k] != 1) ev(k);
		return (query(a,b,k*2+1,l,(l+r)/2)+query(a,b,k*2+2,(l+r)/2+1,r))%mod;
	}
	ll update(int a,int k,int l,int r){
		if(l == a && a == r){
			seg[k] = 1;
			return seg[k];
		}
		if(lazy[k] != 1) ev(k);
		if(l<=a && a<=(l+r)/2){
			return seg[k] = (update(a,k*2+1,l,(l+r)/2)+seg[k*2+2])%mod;
		}
		else{
			return seg[k] = (update(a,k*2+2,(l+r)/2+1,r)+seg[k*2+1])%mod;
		}
	}
	ll mul(ll x){
		seg[0] = seg[0]*x%mod;
		lazy[0] = lazy[0]*x%mod;
	}
}p;
struct BIT
{
	int bit[(1<<18)+5];
	int f(int x)
	{
		return x&-x;
	}
	void add(int i,int x)
	{
		for(int s=i;s<=(1<<18);s+=f(s)) bit[s]+=x;
	}
	int sum(int i)
	{
		int res=0;
		for(int s=i;s>0;s-=f(s)) res+=bit[s];
		return res;
	}
}kaede;
ll modpow(ll x,ll n){
	ll res=1;
	while(n>0){
		if(n&1) res=res*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return res;
}
int n,a[200005],cnt[200005];
vector<int>pos[200005];
int main(){
	scanf("%d",&n);
	repn(i,n){
		scanf("%d",&a[i]);
		pos[a[i]].pb(i);
		cnt[a[i]]++;
	}
	int D = 0;
	ll way = 1;
	for(int i=n;i>=1;i--){
		D += (cnt[i]-1);
		way = way*(D+1)%mod;
		if(D < 0){
			puts("0");
			return 0;
		}
	}
	p.init();
	int zan = 0;
	ll X = 0,Y = 0,ans = 0;
	for(int i=n;i>=1;i--){
		rep(jj,pos[i].size()){
			int j = pos[i][jj];
			int pre = kaede.sum(j-1);
			X = (X+1LL*pre)%mod;
			kaede.add(j,1);
			X += p.query(j+1,n,0,0,(1<<18)-1);
			X %= mod;
			Y += p.query(1,j-1,0,0,(1<<18)-1);
			Y += p.query(j+1,n,0,0,(1<<18)-1);
			Y %= mod;
			p.update(j,0,0,(1<<18)-1);
		}
		zan += pos[i].size();
		ans += (X-Y)%mod*modpow(zan,mod-2)%mod;
		ll pp,qq;
		pp = modpow(zan,mod-2)*(zan-1)%mod;
		qq = modpow(zan-1,mod-2)*(zan-2)%mod;
		X = X*pp%mod;
		Y = Y*pp%mod*qq%mod;
		zan--;
		p.mul(pp);
	}
	printf("%lld\n",(ans%mod+mod)%mod*way%mod);
}