#include <bits/stdc++.h>
#define ll long long
#define maxn 200005 /*rem*/
#define mod 1000000007 
#define db double
#define vi vector<int>
#define pb push_back
#define mp make_pair
#define pi pair<int, int>
#define fi first
#define se second
using namespace std;
ll ksm(ll a, ll b) {
   if (!b) return 1;
   ll ns = ksm(a, b >> 1);
   ns = ns * ns % mod;
   if (b & 1) ns = ns * a % mod;
   return ns;
}
struct bit {
	int d[maxn];
	void init() {
		memset(d, 0, sizeof(d));
	}
	int lb(int a) {
		return a & -a;
	}
	void pls(int pl, int num) {
		while (pl < maxn) {
			d[pl] = (d[pl] + num) % mod;
			pl += lb(pl);
		} 
	}
	int q(int pl) {
		int ans = 0;
		while (pl) 
			ans = (ans + d[pl]) % mod, pl -= lb(pl);
		return ans;
	}
	int q(int l, int r) {
		return (q(r) - q(l - 1)) % mod;
	}
}x;
int n;
int a[maxn], s[maxn], nx[maxn];
ll mt[maxn];
ll re[maxn], br[maxn];
int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		s[a[i]]++;
	}
	for (int i = n; i >= 1; i--)
		s[i] += s[i + 1];
	ll tot = 1;
	for (int i = 1; i <= n; i++) {
		s[i] -= (n - i);
		if (s[i] < 0) {
			cout << 0 << endl;
			return 0;
		}
		tot = tot * s[i] % mod;
		mt[i] = (s[i] - 1) * ksm(s[i], mod - 2) % mod;
	}
	re[0] = 1;
	for (int i = 1; i <= n; i++) {
		re[i] = re[i - 1];
		if (mt[i]) re[i] = re[i] * mt[i] % mod;
		br[i] = ksm(re[i], mod - 2);
	}
	nx[0] = 1;
	for (int i = 1; i <= n; i++)
		if (s[i] == 1) nx[i] = i;
		else nx[i] = nx[i - 1];
	// >= nx[i]
	ll ans = 0;
	for (int i = n; i >= 1; i--)
		ans += x.q(a[i] - 1) * tot, 
		ans %= mod, 
		x.pls(a[i], 1);
	for (int tp = 0; tp < 2; tp++) {
		ll nans = 0;
		x.init();
		for (int i = 1; i <= n; i++) {
			int ns = a[i];
			nans += re[ns] * x.q(nx[ns], ns - tp), nans %= mod;
			x.pls(ns, br[ns]);
		}
		nans = nans * tot % mod;
		nans = nans * (mod + 1) / 2 % mod;
		if (tp == 0) ans += nans;
		else ans -= nans;
		reverse(a + 1, a + n + 1);
	}
	ans %= mod;
	if (ans < 0) ans += mod;
	cout << ans << endl;
	return 0;
}
