#include <bits/stdc++.h>

#define For(i, j, k) for (int i = j; i <= k; i++)
#define Forr(i, j, k) for (int i = j; i >= k; i--)

using namespace std;

const int N = 2e5 + 10;
const int Mod = 1e9 + 7;

int Pow(int x, int e) {
	int ret = 1;
	while (e) {
		if (e & 1) ret = 1ll * ret * x % Mod;
		x = 1ll * x * x % Mod;
		e >>= 1;
	}
	return ret;
}

int n;

struct Binary_Indexed_Tree {

	int c[N], st[N * 20], k;

	void init() {
		while (k) c[st[k--]] = 0;
	}

	int lowbit(int x) {
		return x & (-x);
	}

	void add(int x, int w) {
		while (x <= n) {
			st[++k] = x;
			c[x] = (c[x] + w) % Mod;
			x += lowbit(x);
		}
	}

	int query(int x) {
		int ans = 0;
		while (x) {
			ans = (ans + c[x]) % Mod;
			x -= lowbit(x);
		}
		return ans;
	}

}T;

int A[N], rk[N], cnt[N], d[N];
int pos[N], c;

bool cmp(int x, int y) {
	return A[x] < A[y];
}

int main() {

	scanf("%d", &n);
	For(i, 1, n) scanf("%d", &A[i]), rk[i] = i, ++cnt[A[i]];
	sort(rk + 1, rk + n + 1, cmp);
	Forr(i, n, 1) cnt[i] += cnt[i + 1];
	
	int S = 1;
	For(i, 1, n) {
		cnt[i] -= n - i;
		S = 1ll * S * cnt[i] % Mod;
		if (cnt[i] <= 0) { puts("0"); return 0; }
	}

	int ans = 0;
	Forr(i, n, 1) ans = (ans + T.query(A[i] - 1)) % Mod, T.add(A[i], 1);

	int p = 1;
	For(i, 1, n) {
		int r = i;
		while (r < n && cnt[r + 1] > 1) ++r;
		c = 0;
		while (p <= n && A[rk[p]] <= r) pos[++c] = rk[p], ++p;
		sort(pos + 1, pos + c + 1);

		d[i] = 1;
		For(j, i + 1, r) d[j] = 1ll * d[j - 1] * (cnt[j] - 1) % Mod * Pow(cnt[j], Mod - 2) % Mod;

		T.init();
		For(j, 1, c) {
			int x = A[pos[j]];
			ans = (ans + 1ll * T.query(x) * d[x] % Mod * (Mod + 1) / 2) % Mod;
			T.add(x, Pow(d[x], Mod - 2));
		}
		T.init();
		Forr(j, c, 1) {
			int x = A[pos[j]];
			ans = (ans - 1ll * T.query(x - 1) * d[x] % Mod * (Mod + 1) / 2) % Mod;
			T.add(x, Pow(d[x], Mod - 2));
		}

		i = r;
	}
	ans = 1ll * (ans + Mod) * S % Mod;
	printf("%d\n", ans);

	return 0;
}