#include<bits/stdc++.h>
using namespace std;
#define nn 65536*4
#define ll long long
#define mod 1000000007
ll qpow(ll x,ll y)
{
	ll res=1;
	while(y)
	{
		if(y&1) res=res*x%mod;
		x=x*x%mod;y=y/2;
	}
	return res;
}
struct segmenttree{
	ll tree[nn*2+10];
	#define lc id<<1
	#define rc id<<1|1
	#define mid (l+r)/2
	void update(int x,int y)
	{
		x=x+nn-1;tree[x]=y;x=x/2;int id=x;
		while(x) tree[x]=tree[lc]+tree[rc],tree[x]%=mod,x=x/2,id=x;
	}
	ll query(int a,int b,int l,int r,int id)
	{
		if(a>b) return 0;
		if(l>=a and r<=b) return tree[id];
		ll sm=0;
		if(a<=mid) sm=sm+query(a,b,l,mid,lc);
		if(b>mid) sm=sm+query(a,b,mid+1,r,rc);
		return sm%mod;
	}
}cnt,trcyx;
ll a[nn];ll n;
ll abv[nn];
ll tot;ll pre[nn];
vector<ll> pos[nn];ll ans;
void solve(int l,int r)
{
//	cout<<-r<<" "<<-l<<"\n";
	for(int ii=-l;ii>-r;ii--)
	{
		for(int j=0;j<pos[ii].size();j++)
		{
			ll i=pos[ii][j];
			trcyx.update(i,qpow(pre[a[i]],mod-2));
		}
	}
	
	for(int ii=-l;ii>-r;ii--)
	{
		for(int j=0;j<pos[ii].size();j++)
		{
			ll i=pos[ii][j];
			ll ct=tot*pre[a[i]]%mod*qpow(2,mod-2)%mod;
			ans+=trcyx.query(1,i-1,1,nn,1)*ct%mod;
			
			ans-=trcyx.query(i+1,n,1,nn,1)*ct%mod;
			ans+=cnt.query(i+1,n,1,nn,1)*tot%mod;
			
			cnt.update(i,0);
			trcyx.update(i,0);
			ans%=mod;
		}
	}
	
}
int main()
{
	scanf("%lld",&n);tot=1;pre[0]=1;
	for(int i=1;i<=n;i++) scanf("%lld",&a[i]),abv[a[i]]++,pos[a[i]].push_back(i);
	for(int i=n;i>=1;i--) abv[i]+=abv[i+1],abv[i]%=mod,tot=tot*(abv[i]-(n-i))%mod;
	for(int i=1;i<=n;i++) pre[i]=pre[i-1]*(max(1ll,(abv[i]-(n-i))-1) )%mod*qpow((abv[i]-(n-i)),mod-2)%mod;
	vector<ll> cg;cg.push_back(-0);cg.push_back(-n);
	for(int i=1;i<=n;i++) 
		if(abv[i]-(n-i)==1) 
			cg.push_back(-i+1);
	if(!tot)
	{
		puts("0");
		exit(0);
	}
	
	for(int i=1;i<=n;i++) cnt.update(i,1);
	sort(cg.begin(),cg.end());
	for(int i=0;i<cg.size()-1;i++) solve(cg[i],cg[i+1]);

	printf("%lld\n",(ans+mod)%mod);
	
	return 0;
}