#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 200000 + 10;
const int MOD = 1000000007;

inline int inc(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); }
inline int dec(int a, int b) { return (a >= b) ? (a - b) : (a + MOD - b); }
inline int mul(int a, int b) { return 1LL * a * b % MOD; }

inline int power(int x, int k) {
	int tmp = 1;
	while(k) {
		if(k & 1) tmp = mul(tmp,x);
		x = mul(x,x);
		k >>= 1;
	}
	return tmp;
}

int n;
struct BIT{
	int c[maxn];
	inline void init() { memset(c,0,sizeof(c)); }
	inline int lowbit(int k) { return k & - k; }
	inline void add(int x, int k) {
		for(int i = x;i <= n;i += lowbit(i)) c[i] = inc(c[i],k);
	}
	inline int query(int x) {
		int tmp = 0;
		if(x <= 0) return 0;
		for(int i = x;i;i -= lowbit(i)) tmp = inc(tmp,c[i]);
		return tmp;
	}
	inline int query(int l, int r) {
		if(l > r) return 0;
		return dec(query(r),query(l - 1));
	}
}B1, B2;

int a[maxn], cnt[maxn], pre[maxn], num[maxn], val[maxn], ival[maxn];
int main() {
  scanf("%d", &n);
	for(int i = 1;i <= n;i ++) scanf("%d", &a[i]);
	for(int i = 1;i <= n;i ++) cnt[a[i]] ++;
	cnt[n + 1] = 0;
	for(int i = n;i >= 1;i --) cnt[i] += cnt[i + 1];
	for(int i = 1;i <= n;i ++) cnt[i] -= n - i;
	int Ans = 0, sum = 1;
	for(int i = 1;i <= n;i ++) sum = mul(sum,cnt[i]);
	B1.init(); B2.init();
	val[0] = pre[0] = 1;
  for(int i = 1;i <= n;i ++) {
    int now = mul(cnt[i] - 1,power(cnt[i],MOD - 2));
		if(!now) {
			num[i] = num[i - 1] + 1;
			pre[num[i]] = i;
			val[i] = val[i - 1];
		}
		else {
			num[i] = num[i - 1];
			val[i] = mul(val[i - 1],now);
		}
		ival[i] = power(val[i],MOD - 2);
	}
	int inv2 = power(2,MOD - 2);
	for(int i = 1;i <= n;i ++) {
		int now = mul(B1.query(pre[num[a[i]]],a[i]),val[a[i]]);
		now = mul(now,mul(sum,inv2));
		Ans = inc(Ans,now);
		B1.add(a[i],ival[a[i]]);
	}
	B1.init();
	for(int i = n;i >= 1;i --) {
		int t1 = mul(B1.query(pre[num[a[i]]],a[i] - 1),val[a[i]]);
		int t2 = mul(B2.query(1,a[i] - 1),sum);
		t1 = mul(t1,mul(sum,inv2));
		int now = dec(t2,t1);
		Ans = inc(Ans,now);
		B1.add(a[i],ival[a[i]]);
		B2.add(a[i],1);
	}
	printf("%d\n", Ans);
	return 0;
}	
