#include <bits/stdc++.h>
using namespace std;

const int mod = 1000000007;
const int inv2 = 500000004;

int sum[200010];
long long mul[200010];
int a[200010];
long long inv[200010];
int n;

struct BIT {
	long long T[200010];
	BIT() {memset(T, 0, sizeof(T));}
	void modify(int x, long long v) {
		while (x <= n) (T[x] += v) %= mod, x += x & -x;
	}
	long long query(int x) {
		long long res = 0;
		while (x) (res += T[x]) %= mod, x -= x & -x;
		return res;
	}
};

BIT T1, T2, T3, T;
int zero[200010], num[200010];

long long power(long long a, int b) {
	if (!b) return 1;
	long long tmp = power(a, b >> 1);
	return b & 1 ? tmp * tmp % mod * a % mod : tmp * tmp % mod;
}

int get_left(int x) {
	int l = 0, r = x;
	while (l < r) {
		int mid = l + r >> 1;
		if (num[mid] == num[x]) r = mid;
		else l = mid + 1;
	}
	return l;
}

int get_right(int x) {
	int l = x, r = n + 1;
	while (l < r) {
		int mid = l + r >> 1;
		if (num[mid] == num[x]) l = mid + 1;
		else r = mid;
	}
	return l;
}

int main () {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		sum[a[i]]++;
	}
	for (int i = n; i >= 1; i--) {
		sum[i] += sum[i + 1];
	}
	long long all = 1;
	mul[0] = 1;
	for (int i = 1; i <= n; i++) {
		mul[i] = sum[i] - (n - i);
		(all *= mul[i]) %= mod;
		if (mul[i] == 0) {
			printf("0\n");
			return 0;
		}
		mul[i] = power(mul[i], mod - 2) * (mul[i] - 1) % mod;
		if (mul[i]) (mul[i] *= mul[i - 1]) %= mod;
		else mul[i] = mul[i - 1], num[i] = 1;
		num[i] += num[i - 1];
		inv[i] = power(mul[i], mod - 2);
	}
	if (num[n] == n) {
		long long ans = 0;
		for (int i = n; i >= 1; i--) {
			ans += T.query(a[i] - 1);
			T.modify(a[i], 1);
		}
		printf("%lld\n", ans % mod);
		return 0;
	}
	long long ans = 0;
	for (int i = 1; i <= n; i++) {
		int pos, sum;
		// < a[i]
		pos = get_left(a[i]);
		sum = T1.query(a[i] - 1) - T1.query(pos);
		ans += all * mul[a[i]] % mod * (T3.query(a[i] - 1) - T3.query(pos) + mod) % mod * inv2 % mod;
		// == a[i]
		sum = T1.query(a[i]) - T1.query(a[i] - 1);
		ans += all * inv2 % mod * sum % mod;
		// > a[i]
		pos = get_right(a[i]) - 1;
		sum = T1.query(n) - T1.query(a[i]);
		ans += all * sum % mod - all * inv[a[i]] % mod * (T2.query(pos) - T2.query(a[i]) + mod) % mod * inv2 % mod + mod;
		T1.modify(a[i], 1), T2.modify(a[i], mul[a[i]]), T3.modify(a[i], inv[a[i]]);
		ans %= mod;
	}
	printf("%lld\n", ans);
	return 0;
}
