#include<cstdio>
using namespace std;
#define N 300500
#define mod 1000000007
int n,p[N],su[N],v[N],su1[N],as,as1,tr[N],lb[N],tr2[N],rb[N],tr3[N];
int pw(int a,int p){int as=1;while(p){if(p&1)as=1ll*as*a%mod;a=1ll*a*a%mod;p>>=1;}return as;}
void add(int x,int k){for(int i=x;i<=n;i+=i&-i)tr[i]=(tr[i]+k)%mod;}
int que(int x){int as=0;for(int i=x;i;i-=i&-i)as=(as+tr[i])%mod;return as;}
void add2(int x,int k){for(int i=x;i<=n;i+=i&-i)tr2[i]+=k;}
int que2(int x){int as=0;for(int i=x;i;i-=i&-i)as+=tr2[i];return as;}
void add3(int x,int k){for(int i=x;i<=n;i+=i&-i)tr3[i]=(tr3[i]+k)%mod;}
int que3(int x){int as=0;for(int i=x;i;i-=i&-i)as=(as+tr3[i])%mod;return as;}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&p[i]),su[p[i]]++;
	for(int i=n-1;i>=1;i--)su[i]=su[i+1]+su[i]-1;
	as=1;
	for(int i=1;i<=n;i++)as=1ll*as*su[i]%mod;
	if(!as){printf("0\n");return 0;}
	lb[0]=1;
	for(int i=1;i<=n;i++)
	{
		v[i]=1ll*(su[i]-1)*pw(su[i],mod-2)%mod;
		su1[i]=v[i];if(su1[i-1])su1[i]=1ll*su1[i]*su1[i-1]%mod;
	}
	for(int i=n;i>=1;i--)if(v[i+1])rb[i]=rb[i+1];else rb[i]=i;
	for(int i=1;i<=n;i++)if(v[i-1])lb[i]=lb[i-1];else lb[i]=i;
	for(int i=1;i<=n;i++)
	{
		int su11=que(p[i])-que(lb[p[i]]-1),su2=que2(p[i])-que2(lb[p[i]]-1);
		as1=(as1+1ll*as*su11%mod*su1[p[i]]%mod*(mod+1)/2)%mod;
		su11=que3(rb[p[i]])-que3(p[i]),su2=que2(n)-que2(p[i]);
		as1=(as1+1ll*as*su2%mod-1ll*as*su11%mod*pw(su1[p[i]],mod-2)%mod*(mod+1)/2%mod)%mod;
		add(p[i],pw(su1[p[i]]?su1[p[i]]:1,mod-2)),add2(p[i],1);add3(p[i],su1[p[i]]);
	}
	printf("%d\n",(as1+mod)%mod);
}