#include <bits/stdc++.h>

using namespace std;

const int N = 200005;
const int mod = 1e9 + 7;

int n;
int all;
int res;
int a[N], b[N];
int lim[N];
int prd[N];
int bit[N];
int bit2[N];

int binPow(int x, int y) {
	if (!y) return 1; 
	int ret = binPow(x, y >> 1);
	ret = 1LL * ret * ret % mod; 
	if (y & 1) ret = 1LL * ret * x % mod;
	return ret;
}

void upd(int x, int y) {
	for (; x <= n; x += x & -x) bit[x] = (bit[x] + y) % mod;
}

int get(int x) {
	int ret = 0;
	for (; x > 0; x -= x & -x) ret = (ret + bit[x]) % mod;
	return ret;
}

void upd2(int x) {
	for (; x <= n; x += x & -x) bit2[x]++;
}

int get2(int x) {
	int ret = 0;
	for (; x > 0; x -= x & -x) ret += bit2[x];
	return ret;
}

int get(int l, int r) { return get(r) - get(l - 1); }

int main() {
	ios::sync_with_stdio(false);
	cin >> n;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i], b[a[i]]++;
	}
	for (int i = n - 1; i >= 1; --i) b[i] += b[i + 1] - 1;
	for (int i = n; i >= 1; --i) {
		if (b[i] <= 0) {
			cout << 0; return 0;
		}
	}
	all = 1;
	for (int i = 1; i <= n; ++i) all = 1LL * all * b[i] % mod;
	int cur = 1;
	for (int i = 1; i <= n; ++i) {
		if (b[i] == 1) cur = i; lim[i] = cur;
	}
	prd[0] = 1;
	for (int i = 1; i <= n; ++i) {
		if (b[i] == 1) prd[i] = prd[i - 1];
		else prd[i] = 1LL * prd[i - 1] * (b[i] - 1) % mod * binPow(b[i], mod - 2) % mod;
	}
	for (int i = 1; i <= n; ++i) {
		res = (res + 1LL * prd[a[i]] * get(lim[a[i]], a[i]) % mod * all) % mod; 
		upd(a[i], binPow(prd[a[i]], mod - 2));
	}
	memset(bit, 0, sizeof bit);
	long long cnt = 0;
	for (int i = n; i >= 1; --i) {
		res = (res - 1LL * prd[a[i]] * get(lim[a[i]], a[i] - 1) % mod * all) % mod; 
		if (res < 0) res += mod;
		cnt += get2(a[i] - 1);
		upd(a[i], binPow(prd[a[i]], mod - 2));		
		upd2(a[i]);
	}
	res = 1LL * res * binPow(2, mod - 2) % mod;
	res = (res + cnt % mod * all) % mod;
	cout << res;
}