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

namespace TYC
{
	typedef long long ll;
	typedef pair<int, int> pii;

	const int N = 3e5 + 10;
	const int mod = 1e9 + 7, INV2 = (mod + 1) >> 1;

	int n, S, A[N], Cnt[N], D[N], PD[N], C1[N], C2[N];
	pii P[N];


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

	inline int inv(const int x) { return qpow(x, mod - 2); }

#define lowbit(x) (x & (-x))

	inline void add(int x)
	{
		int w = PD[A[x]];
		for (; x <= n; x += lowbit(x)) 
			C1[x]++, C2[x] = (C2[x] + w) % mod;
	}

	inline void del(int x)
	{
		int w = (mod - PD[A[x]]) % mod;
		for (; x <= n; x += lowbit(x))
			C2[x] = (C2[x] + w) % mod;
	}

	inline int getnum(int x)
	{
		if (!x)
			return 0;
		int ans = 0;
		for (; x; x -= lowbit(x))
			ans += C1[x];
		return ans;
	}

	inline int getsum(int x)
	{
		if (!x)
			return 0;
		int ans = 0;
		for (; x; x -= lowbit(x))
			ans = (ans + C2[x]) % mod;
		return ans;
	}

	void init()
	{
		for (int i = n - 1; i; i--)
			Cnt[i] += Cnt[i + 1];
		S = 1;
		for (int i = 1; i <= n; i++)
		{
			Cnt[i] -= (n - i);
			S = (ll)S * Cnt[i] % mod;
			D[i] = (ll)(Cnt[i] - 1 + mod) * inv(Cnt[i]) % mod;
		}
		for (int i = 1; i <= n; i++)
			if (!D[i - 1])
				PD[i] = D[i];
			else
				PD[i] = (ll)PD[i - 1] * D[i] % mod;
	}

	void work()
	{
		scanf("%d", &n);
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &A[i]);
			Cnt[A[i]]++;
			P[i] = pii(A[i], i);
		}
		sort(P + 1, P + 1 + n, greater<pii>());
		init();
		if (!S)
			return void(puts("0"));
		
		int l = 1, r, last = 1, ans = 0;
		for (int val = n; val; val--)
		{
			if (P[l].first == val)
			{
				for (r = l; r < n && val == P[r + 1].first; ++r);
				int num = r - l + 1;
				if (num > 1)
					ans = (ans + (ll)num * (num - 1) / 2 % mod * S % mod * INV2) % mod;
				int t = D[val] ? inv(PD[val]) : 1;
				for (int i = l; i <= r; i++)
				{
					int p = P[i].second;
					ans = (ans + (ll)(getsum(n) - getsum(p)) * S % mod * t % mod * INV2) % mod;
					ans = (ans - (ll)getsum(p - 1) * S % mod * t % mod * INV2 % mod + mod) % mod;
					ans = (ans + (ll)getnum(p - 1) * S) % mod;
				}
				for (int i = l; i <= r; i++)
					add(P[i].second);
				l = r + 1;
			}
			if (!D[val])
			{
				for (int i = last; i < l; i++)
					del(P[i].second);
				last = l;
				continue;
			}
		}
		printf("%d\n", ans);
	}
}

int main()
{
	TYC::work();
	return 0;
}