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

const int maxN = 2e5 + 100, mod = 1e9 + 7;

int n, a[maxN + 1], cnt[maxN + 1];
int s[maxN + 1], pre[maxN + 1];
int C[maxN + 1], ans, tmp, r[maxN + 1], sum[maxN + 1];

inline int read()
{
	int num = 0, f = 1;
	char ch = getchar();
	while( !isdigit( ch ) ) { if(ch == '-') f = -1; ch = getchar(); }
	while( isdigit( ch ) ) num = (num << 3) + (num << 1) + (ch ^ 48), ch = getchar();
	return num * f;
}

inline int mpow(int a, int x)
{
	int ans = 1;
	while(x)
	{
		if(x & 1) ans = 1ll * ans * a % mod;
		a = 1ll * a * a % mod;
		x >>= 1;
	}
	return ans;
}

inline int ADD(int x, int y) { return x + y >= mod ? x + y - mod : x + y; }

inline int SUB(int x, int y) { return x - y < 0 ? x - y + mod : x - y; }

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

inline void change(int x, int num)
{
	for(int i = x; i <= n; i += lowbit(i)) C[i] = ADD(C[i], num);
}

inline int query(int x)
{
	int ans = 0;
	for(int i = x; i; i ^= lowbit(i)) ans = ADD(ans, C[i]);
	return ans;
}

int main()
{
	n = read();
	for(int i = 1; i <= n; i++) a[i] = read(), cnt[ a[i] ] ++;
	for(int i = n; i >= 1; i--) cnt[i] += cnt[i + 1];
	s[0] = 1; tmp = 1;
	for(int i = 1; i <= n; i++)
	{
		cnt[i] -= (n - i);
		if(cnt[i] <= 0) { puts("0"); return 0; }
		int t = 1ll * (cnt[i] - 1) * mpow(cnt[i], mod - 2) % mod;
		if(t == 0) pre[i] = pre[i - 1] + 1, s[i] = s[i - 1];
		else pre[i] = pre[i - 1], s[i] = 1ll * s[i - 1] * t % mod;
		tmp = 1ll * tmp * cnt[i] % mod;
		r[ pre[i] ] = i;
	}
	int inv = mpow(2, mod - 2);
	for(int i = n; i >= 1; i--)
	{
		ans = ADD(ans, 1ll * tmp * SUB(query(r[ pre[ a[i] ] ]), query(a[i] - 1)) % mod * mpow(s[ a[i] ], mod - 2) % mod * inv % mod);
		change(a[i], s[ a[i] ]);
	}
	memset(C, 0, sizeof(C));
	for(int i = 1; i <= n; i++)
		sum[i] = SUB(query(n), query(a[i])), change(a[i], 1);
	memset(C, 0, sizeof(C));
	for(int i = 1; i <= n; i++)
	{
		ans = ADD(ans, SUB(1ll * tmp * sum[i] % mod, 1ll * tmp * SUB(query(r[ pre[ a[i] ] ]), query(a[i])) % mod * mpow(s[ a[i] ], mod - 2) % mod * inv % mod));
		change(a[i], s[ a[i] ]);
	}
	printf("%d", ans);
	return 0;
}