#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define Mod 1000000007
using namespace std;
int n;
int fpow(int a,int b)
{
	int ans=1,t=a;
	while(b)
	{
		if(b&1)ans=(long long)ans*t%Mod;
		t=(long long)t*t%Mod;
		b>>=1;
	}
	return ans;
}
struct Fenwick{
	int c[200010];
	inline int lowbit(int x)
	{
		return x&(-x);
	}
	void add(int x,int y)
	{
		for(;x<=n;x+=lowbit(x))
			c[x]=(c[x]+y)%Mod;
		return ;
	}
	int query(int x)
	{
		int ans=0;
		for(;x;x-=lowbit(x))
			ans=(ans+c[x])%Mod;
		return ans;
	}
	void clear()
	{
		memset(c,0,sizeof(c));
		return ;
	}
}F;
int cnt[200010],num[200010];
int to[200010];
int A[200010];
int f[200010],g[200010];
int calcf(int l,int r)
{
	return (long long)f[r]*fpow(f[l-1],Mod-2)%Mod;
}
int calcg(int l,int r)
{
	if(to[l+1]>r)
		return (long long)g[r]*fpow(g[l-1],Mod-2)%Mod;
	return 0;
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&A[i]),cnt[A[i]]++;
	int all=1;
	for(int i=n;i>=1;i--)
	{
		if(i<n)cnt[i]+=cnt[i+1]-1;
		all=(long long)all*cnt[i]%Mod;
		if(!cnt[i]){
			printf("0\n");
			return 0;
		}
	}
	f[0]=1,g[0]=1;
	for(int i=1;i<=n;i++)
	{
		f[i]=(long long)cnt[i]*f[i-1]%Mod;
		if(cnt[i]>1)g[i]=(long long)g[i-1]*(cnt[i]-1)%Mod;
		else g[i]=g[i-1];
	}
	to[n+1]=n+1;
	for(int i=n;i>=1;i--)
		if(cnt[i]==1)to[i]=i;
		else to[i]=to[i+1];
	//A[i]<A[j]
	int ans=0;
	for(int i=n;i>=1;i--)
	{
		int res=((long long)F.query(to[A[i]+1]-1)-F.query(A[i])+Mod)%Mod*cnt[A[i]]%Mod*f[A[i]-1]%Mod*fpow(g[A[i]],Mod-2)%Mod;
		ans=(ans+(long long)res*fpow(2,Mod-2))%Mod;
		F.add(A[i],(long long)calcf(A[i]+1,n)*g[A[i]]%Mod);
	}
	//A[i]=A[j]
	for(int i=1;i<=n;i++)
		num[A[i]]++;
	for(int i=1;i<=n;i++)
		ans=(ans+((long long)num[i]*(num[i]-1)/2)%Mod*all%Mod*fpow(2,Mod-2))%Mod;
	//A[i]>A[j]
	F.clear();memset(num,0,sizeof(num));
	for(int i=1;i<=n;i++)
	{
		num[i]=F.query(n)-F.query(A[i]);
		F.add(A[i],1);
	}
	F.clear();
	for(int i=1;i<=n;i++)
	{
		int res=((long long)F.query(to[A[i]+1]-1)-F.query(A[i])+Mod)%Mod*cnt[A[i]]%Mod*f[A[i]-1]%Mod*fpow(g[A[i]],Mod-2)%Mod;
		ans=((ans+(long long)num[i]*all%Mod-(long long)res*fpow(2,Mod-2)%Mod)%Mod+Mod)%Mod;
		F.add(A[i],(long long)calcf(A[i]+1,n)*g[A[i]]%Mod);
	}
	printf("%d\n",ans);
	return 0;
}
