#include <iostream>
#include <cstdio>
#include <cstring> 
#define MN 201000
#define mod 1000000007

int inv[MN], cnt[MN], a[MN], nxt[MN];
int f[MN], s[MN];
int c[MN];
int n; 

int qpow(int x, int p)
{
	int ans = 1;
	for(; p; p >>= 1, x = 1ll * x * x % mod) if(p & 1) ans = 1ll * ans * x % mod;
	return ans;
}

void add(int x, int v) {for(int i = x; i <= n; i += i & -i) c[i] = (c[i] + v) % mod;}
int query(int x) {int ans = 0; for(int i = x; i; i -= i & -i) ans = (ans + c[i]) % mod; return ans;}

int main()
{
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
		cnt[a[i]]++;
	}
	int tot = 1, ans = 0;
	nxt[n] = n; for(int i = n - 1; i >= 1; i--) cnt[i] += cnt[i + 1] - 1, nxt[i] = cnt[i + 1] == 1 ? i : nxt[i + 1];
	for(int i = 1; i <= n; i++) tot = 1ll * tot * cnt[i] % mod;
	inv[0] = inv[1] = 1;
	for(int i = 2; i <= n; i++) inv[i] = 1ll * (mod - mod / i) * inv[mod % i] % mod;
	s[0] = 1; for(int i = 1; i <= n; i++) s[i] = 1ll * s[i - 1] * (cnt[i] == 1 ? 1 : 1ll * inv[cnt[i]] * (cnt[i] - 1) % mod) % mod;
	for(int i = 1; i <= n; i++) f[i] = (1ll * f[i - 1] * inv[cnt[i]] % mod * (cnt[i] - 2) + 1ll * tot * inv[cnt[i]]) % mod;
	for(int i = n; i >= 1; i--)
	{
		ans = (ans + 1ll * f[a[i]] * (query(nxt[a[i]]) - query(a[i] - 1) + mod) % mod * qpow(s[a[i]], mod - 2)) % mod;
		add(a[i], s[a[i]]);
	}
	memset(c, 0, sizeof(c)); 
	for(int i = 1; i <= n; i++)
	{
		ans = (ans - 1ll * f[a[i]] * (query(nxt[a[i]]) - query(a[i]) + mod) % mod * qpow(s[a[i]], mod - 2) % mod + mod) % mod;
		add(a[i], s[a[i]]);
	}
	memset(c, 0, sizeof(c));
	for(int i = 1; i <= n; i++)
	{
		ans = (ans + 1ll * (query(n) - query(a[i])) * tot) % mod;
		add(a[i], 1);
	}
	printf("%d\n", ans);
}