#include <bits/stdc++.h>
#define rep(i, n) for (rint i = 1; i <= (int)(n); i ++)
#define re0(i, n) for (rint i = 0; i < (int) n; i ++)
#define travel(i, u) for (rint i = head[u]; i; i = e[i].nxt)
#define rint register int
using namespace std;

typedef long long lo;

template<typename tp> inline void read(tp &x) {
    x = 0; char c = getchar(); int f = 0;
    for (; c < '0' || c > '9'; f |= c == '-', c = getchar());
    for (; c >= '0' && c <= '9'; x = (x << 3) + (x << 1) + c - '0', c = getchar());
    if (f) x = -x;
}
namespace {
    const int mo = 1e9 + 7;
    inline int add(int x, int y) { x += y; return x >= mo ? x - mo : x; }
    inline int sub(int x, int y) { x -= y; return x < 0 ? x + mo : x; }
    inline int mul(int x, int y) { return (lo) x * y % mo; }
    inline int power(int a, int k = mo - 2) {
		int ans = 1;
		for (; k; k >>= 1, a = mul(a, a))
			if (k & 1) ans = mul(ans, a);
		return ans;
    }
	inline void U(int &x, int y) { x = add(x, y); } 
}

const int N = 3e5 + 233; 
int n, a[N], id[N], rnk[N], val[N], pre[N], pid[N], sum[N], isum[N];

struct bit_t {
	int tr[N];
	inline void init() {
		memset(tr, 0, sizeof tr);
	}
	inline void add(int x, int v) {
		for (; x < N; x += x & -x) U(tr[x], v);
	}
	inline int _query(int x) {
		if (x <= 0) return 0;
		int ans = 0;
		for (; x >= 1; x -= x & -x) U(ans, tr[x]);
		return ans;
	}
	inline int query(int l, int r) {
		return l > r ? 0 : sub(_query(r), _query(l - 1));
	}
} L, R;

int main(void) {
	read(n);
	rep (i, n) read(a[i]), id[i] = i;
	sort(id + 1, id + n + 1, [](int x, int y) {
			return a[x] < a[y];
		});
	rep (i, n) {
		rnk[id[i]] = i;
		val[i] = mul(a[id[i]] - (i - 1) - 1, power(a[id[i]] - (i - 1)));
		isum[i] = power(sum[i] = mul(sum[i - 1] == 0 ? 1 : sum[i - 1], val[i]));
		pre[i] = val[i] == 0 ? i : pre[i - 1];
		pid[i] = a[id[i]] == a[id[i - 1]] ? pid[i - 1] : i - 1;
	}
	int all = 1;
	rep (i, n) {
		if (a[i] - (rnk[i] - 1) <= 0)
			return puts("0"), 0;
		all = mul(all, a[i] - (rnk[i] - 1));
	}
	int ans = 0;
	{
		map <int, int> mp;
		rep (i, n) mp[a[i]]++;
		for (auto i : mp) U(ans, mul((lo) i.second * (i.second - 1) / 2, mul(power(2), all)));
	}
	{
		int coef = 0, tot = 0;
		L.init(); R.init();
		for (int i = n; i >= 1; i--) {
			int u = rnk[i];
			U(coef, mul(mul(sum[u - 1], L.query(pre[u - 1] + 1, pid[u])), power(a[i] - (u - 1))));
			L.add(u, mul(isum[u], a[i] - u));
			U(tot, R.query(1, pid[u]));
			R.add(u, 1);
		}
		U(ans, mul(all, sub(tot, mul(power(2), coef))));
	}
	{
		L.init();
		int coef = 0;
		for (int i = 1; i <= n; i++) {
			int u = rnk[i];
			U(coef, mul(mul(sum[u - 1], L.query(pre[u - 1] + 1, pid[u])), power(a[i] - (u - 1))));
			L.add(u, mul(isum[u], a[i] - u));
		}
		U(ans, mul(coef, mul(power(2), all)));
	}
	cout << ans << "\n";
}
