#include <bits/stdc++.h>
#define M 1000005
#define mod 1000000007
#define inv2 500000004ll
#define PB push_back
#define MP std::make_pair
#define FI first
#define SE second
typedef long long ll;
int n, A[M], B[M], F[M], invF[M], col[M], S[M];
ll fac[M], fac_inv[M], inv[M];
std::vector <int> Vec[M];
int read() {
	char c = getchar(); int ans = 0;
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9') ans = ans * 10 + c - '0', c = getchar();
	return ans;
}
void Write(int x) {
	if (x < 10) putchar(x + '0');
	else Write(x / 10), putchar(x % 10 + '0');
}
int Add(int x, int y) {return (x += y) >= mod ? x - mod : x;}
void add(int &x, int y) {if ((x += y) >= mod) x -= mod;}
ll invs(int x) {return x == 1 ? 1 : (mod - mod / x) * invs(mod % x) % mod;}
void init_mod(int n) {
	fac[0] = 1;
	for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % mod; fac_inv[n] = invs(fac[n]);
	for (int i = n; i; i--) fac_inv[i - 1] = fac_inv[i] * i % mod;
	for (int i = 1; i <= n; i++) inv[i] = fac[i - 1] * fac_inv[i] % mod;
}
namespace BIT {
	#define lowbit(x) (x & -x)
	int X[M];
	void Insert(int x, int y) {while (x <= n) add(X[x], y), x += lowbit(x);}
	int query(int x) {int ans = 0; while (x) add(ans, X[x]), x -= lowbit(x); return ans;}
	#undef lowbit
}
int solve(int l, int r, int id) {
	F[l] = invF[l] = 1; ll ans = 0;
	for (int i = l + 1; i <= r; i++)
		F[i] = F[i - 1] * (B[i] - 1ll) % mod * inv[B[i]] % mod,
		invF[i] = invF[i - 1] * inv[B[i] - 1] % mod * B[i] % mod;
	for (auto i : Vec[id]) ans = (ans + (ll)BIT::query(i - 1) * F[i]) % mod, BIT::Insert(i, invF[i]);
	for (auto i : Vec[id]) BIT::Insert(i, mod - invF[i]);
	for (auto i : Vec[id]) ans = (ans - (ll)BIT::query(n - i) * invF[i]) % mod, BIT::Insert(n + 1 - i, F[i]);
	for (auto i : Vec[id]) BIT::Insert(n + 1 - i, mod - F[i]);
	return ans;
}
ll calc() {
	ll ans = 0;
	for (int i = 1; i <= n; i++)
		ans += i - 1 - BIT::query(A[i]), BIT::Insert(A[i], 1);
	return ans;
}
int main() {
	n = read(); ll tmp = 1, ans = 0; init_mod(n);
	for (int i = 1; i <= n; i++) ++B[A[i] = read()];
	for (int i = n; i; i--) ans += B[i] * (B[i] - 1ll) / 2, B[i] += B[i + 1];
	for (int i = 1; i <= n; i++) tmp = tmp * (B[i] -= (n - i)) % mod;
	if (tmp == 0) return putchar('0'), 0; if (B[1] != 1) S[++*S] = 1;
	for (int i = 1; i <= n; i++) if (B[i] == 1) S[++*S] = i; S[++*S] = n + 1;
	for (int i = 1; i < *S; i++) std::fill(col + S[i], col + S[i + 1], i);
	for (int i = 1; i <= n; i++) Vec[col[A[i]]].PB(A[i]);
	for (int i = 1; i < *S; i++) ans += solve(S[i], S[i + 1] - 1, i);
	ans = (ans + 2 * calc()) % mod * tmp % mod * inv2 % mod;
	return Write((ans + mod) % mod), 0;
}
