#include<bits/stdc++.h> 
#define ll long long 
#define de() cout<<"test"<<"\n" 
using namespace std;
const int maxn=2e6+10;
const int mod=1000000007;
inline int read() {
	int data=0,f=1;char c=getchar();
	while('0'>c||c>'9') {
		if(c=='-') f=-1;c=getchar();
	}while('0'<=c&&c<='9') {
		data=data*10+c-'0';c=getchar();
	}return data*f;
}

int a[maxn],cnt[maxn],n,z1[maxn];
ll z2[maxn];
int lb(int x) { 
	return x&(-x);
}
void add(int x,int w) {
	for(int i=x;i<=n;i+=lb(i)) {
		z1[i]++;z2[i]=(z2[i]+w)%mod;
	}
}
ll sum1(int x) {
	ll ans=0;
	for(int i=x;i;i-=lb(i)) ans+=z1[i];
	return ans;
}
ll sum2(int x) {
	ll ans=0;//cout<<x<<"\n";
	for(int i=x;i;i-=lb(i)) ans=(ans+z2[i])%mod;
	return ans;
}
ll poww(ll x,ll k) {
	ll ans=1;
	while(k) {
		if(k&1) ans=ans*x%mod;
		x=x*x%mod;
		k>>=1;
	}
	return ans;
}
ll tot=1,D[maxn],invD[maxn],ans,inv2;
int s[maxn],ze[maxn];

int main() 
{
	scanf("%d",&n);inv2=poww(2,mod-2);
	for(int i=1;i<=n;++i) scanf("%d",&a[i]),cnt[a[i]]++;
	for(int i=n;i;i--) cnt[i]+=cnt[i+1];
	for(int i=n;i;i--) tot=tot*(cnt[i]-(n-i))%mod,cnt[i]-=(n-i);
	D[0]=s[0]=1;
	if(tot==0) {
		puts("0");return 0;
	}
	for(int i=1;i<=n;++i) { 
		ll x=1ll*(cnt[i]-1)*poww(cnt[i],mod-2)%mod; 
		if(!x) { 
			s[ze[i]=ze[i-1]+1]=i;D[i]=D[i-1];
		} else ze[i]=ze[i-1],D[i]=D[i-1]*x%mod;
		invD[i]=poww(D[i],mod-2);
	}
	//for(int i=1;i<=n;++i) cout<<ze[i]<<"*\n";
	//puts("");
	for(int i=1;i<=n;++i) { 
		ans=(ans+(sum2(a[i])-sum2(s[ze[a[i]]]-1)+mod)*D[a[i]]%mod*tot%mod*inv2%mod)%mod;
		add(a[i],invD[a[i]]);  
	} 
	for(int i=0;i<=n;++i) z1[i]=z2[i]=0;
	for(int i=n;i;i--) { 
		ans=(ans-(sum2(a[i]-1)-sum2(s[ze[a[i]]]-1)+mod)*D[a[i]]%mod*tot%mod*inv2%mod+mod)%mod; 
		ans=(ans+1ll*tot*sum1(a[i]-1)%mod)%mod;
		add(a[i],invD[a[i]]);
	}
	cout<<ans<<"\n";
	return 0;
} 