#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define il inline
#define db double
#define ls rt << 1
#define rs rt << 1 | 1
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define X first
#define Y second
#define pcc pair<char, char>
#define vi vector<int>
#define vl vector<ll>
#define rep(i, x, y) for(int i = x; i <= y; i ++)
#define rrep(i, x, y) for(int i = x; i >= y; i --)
#define rep0(i, n) for(int i = 0; i < (n); i ++)
#define per0(i, n) for(int i = (n) - 1; i >= 0; i --)
#define ept 1e-9
#define INF 0x3f3f3f3f
#define sz(x) (x).size()
#define ALL(x) (x).begin(), (x).end()
#define ite iterator
using namespace std;
inline int read()
{
	int x = 0, f = 1; char ch = getchar();
	while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * f;
}
inline ll read1()
{
	ll x = 0, f = 1; char ch = getchar();
	while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
 	return x * f;
}
using namespace std;
const int mod = 1e9 + 7;

const int N = 3e5 + 10;
int *s1[N],*s2[N],s[N],tot[N],cnt;
int id[N],pos[N];
int a[N],sum[N],val[N],inv[N];
int n,num,ans;void inc(int &x,const int &y)
{
	if((x += y) >= mod) x -= mod;
}
 
void ins(int *sum,int n,int p,int v)
{
	while(p <= n) inc(sum[p], v), p += p & -p;
}
 
int qry(int *sum,int p)
{
	int ans = 0;
	while(p) inc(ans,sum[p]), p -= p & -p;
	return ans;
}
 
int qry2(int *sum,int n,int p)
{
	return (qry(sum, n) - qry(sum, p - 1) + mod) % mod;
}
 
il ll qpow(ll x,int y)
{
	ll ans = 1;
	while(y)
	{
		if(y & 1) ans = ans * x % mod;
		x = x * x % mod;
		y >>= 1;
	}
	return ans;
}
 
int main()
{
	n = read();
	rep(i, 1, n)
	{
		a[i] = read();
		sum[a[i]] ++;
	}
	rrep(i, n - 1, 1) sum[i] += sum[i + 1];
	int lst = 0;
	num = 1;
	rep(i, 1, n)
	{
		int v = sum[i] - n + i;
		if(!v) return puts("0"), 0;
		num = (ll)num * v % mod;
		val[i] = (v - 1) * qpow(v, mod - 2) % mod;
		if(val[i - 1]) val[i] = (ll)val[i] * val[i - 1] % mod;
		inv[i] = qpow(val[i], mod - 2);
		if(!val[i])
		{
			tot[++ cnt] = i - lst;
			rep(j, lst, i - 1) id[j] = cnt, pos[j] = j - lst + 1;
			lst = i;
			val[i] = inv[i] = 1;
		}
	}
	tot[++ cnt] = n + 1 - lst;
	rep(i, 1, cnt)
	{
		s1[i] = new int[tot[i] + 1];
		s2[i] = new int[tot[i] + 1];
		memset(s1[i], 0, sizeof(int)*(tot[i]+1));
		memset(s2[i], 0, sizeof(int)*(tot[i]+1));
	}
	rep(j, lst, n) id[j] = cnt, pos[j] = j - lst + 1;
	ll inv2 = qpow(2, mod - 2);
	rep(i, 1, n)
	 {
		int v=a[i],j=id[v],p=pos[v];
		inc(ans,(ll)num*qry(s2[j],p)%mod*val[v]%mod*inv2%mod);
		inc(ans,(ll)num*((ll)qry2(s,n,v+1)+mod-(ll)qry2(s1[j],tot[j],p+1)*inv[v]%mod*inv2%mod)%mod);
		ins(s1[j],tot[j],p,val[v]);
		ins(s2[j],tot[j],p,inv[v]);
		ins(s,n,v,1);
	}
	printf("%d\n",ans);
	return 0;
}
