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

const int N = 200010;
const int mod = 1e9 + 7;
const int inv2 = (mod + 1) / 2;

typedef long long LL;

inline int Pow(int x, int y) {
    int res = 1;
    for (; y; y >>= 1, x = (LL)x * x % mod) if (y & 1) res = (LL)res * x % mod;
    return res;
}

int n;

struct FUCK {
	
int tree[N];
    
inline void update(int x, int y) {
    for (; x <= n; x += x & -x) tree[x] = (tree[x] + y) % mod;
}

inline int query(int x) {
    int res = 0;
    for (; x; x -= x & -x) res = (res + tree[x]) % mod;
    return res;
}

inline int query(int l, int r) {
    return (query(r) - query(l - 1) + mod) % mod;
}

} X, Y, Z;

int A[N], num[N], pre[N], lst[N], nxt[N], ct[N];
bool fuck[N];

int main() {
	scanf("%d", &n);
	for (int i = 1, a; i <= n; i++) scanf("%d", &a), A[a]++, num[i] = a;
	for (int i = n; i >= 0; i--) A[i] += A[i + 1];
	int tot = 1; pre[0] = 1;
	for (int i = 1; i <= n; i++) {
		A[i] -= n - i, tot = (LL)tot * A[i] % mod;
		if (A[i] <= 0) return puts("0"), 0;
		int t = (LL)(A[i] - 1) * Pow(A[i], mod - 2) % mod;
		if (t) pre[i] = (LL)pre[i - 1] * t % mod;
		else pre[i] = pre[i - 1], fuck[i] = true;
	} 
	nxt[n + 1] = n + 1;
	for (int i = n; i >= 1; i--) {
		nxt[i] = nxt[i + 1];
		if (fuck[i]) nxt[i] = i;
	}
	for (int i = 1; i <= n; i++) {
		lst[i] = lst[i - 1];
		if (fuck[i]) lst[i] = i;
	}
	int res = 0;
	for (int i = 1; i <= n; i++) {
		res = (res + (LL)ct[num[i]] * tot % mod * inv2) % mod;
		if (num[i] != 1) {
			res = (res + (LL)Y.query(max(1, lst[num[i]]), num[i] - 1) * pre[num[i]] % mod
				* tot % mod * inv2) % mod;
		}
		if (num[i] != n) {
			res = (res + (LL)Z.query(num[i] + 1, n) * tot) % mod;
			res = (res - (LL)X.query(num[i] + 1, min(n, nxt[num[i] + 1] - 1)) * Pow(pre[num[i]], mod - 2) % mod
				* tot % mod * inv2 % mod + mod) % mod;
		}
		X.update(num[i], pre[num[i]]), Y.update(num[i], Pow(pre[num[i]], mod - 2)), Z.update(num[i], 1), ct[num[i]]++;
	}
	printf("%d\n", res);
}//