#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define mod 1000000007LL
#define lowbit(x) ((x)&(-(x)))

pii h[200010];

int num[200010],cnt[200010],c[200010],n;

inline int rd()
{
	int x=0;char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar());
	for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
	return x;
}

inline ll pls(const ll &x,const ll &y) { return (x+y<mod)?x+y:x+y-mod; }
inline ll mns(const ll &x,const ll &y) { return (x-y<0)?x-y+mod:x-y; }
inline ll ksm(ll x,ll y) { ll res=1;for (;y;y>>=1,x=x*x%mod) if (y&1) res=res*x%mod;return res; }

const ll inv2=ksm(2,mod-2);

inline void add(int x) { for (;x<=n;x+=lowbit(x)) c[x]++; }

inline int getsum(int x)
{
	int res=0;
	for (;x;x-=lowbit(x)) res+=c[x];
	return res;
}

ll sum[800010],tag[800010];

inline void gao(const int &o,const ll &hh) { sum[o]=sum[o]*hh%mod;tag[o]=tag[o]*hh%mod; }

inline void pushup(const int &o) { sum[o]=pls(sum[o<<1],sum[o<<1|1]); }

inline void pushdown(const int &o)
{
	if (tag[o]==1) return;
	gao(o<<1,tag[o]);gao(o<<1|1,tag[o]);
	tag[o]=1;
}

inline void build(int o,int l,int r)
{
	sum[o]=0;tag[o]=1;
	if (l==r) return;
	int mid=(l+r)>>1;
	build(o<<1,l,mid);
	build(o<<1|1,mid+1,r);
}

inline void modify(int o,int l,int r,int x,ll y)
{
	if (l==r) { sum[o]=y;return; }
	pushdown(o);
	int mid=(l+r)>>1;
	if (x<=mid) modify(o<<1,l,mid,x,y);
	else modify(o<<1|1,mid+1,r,x,y);
	pushup(o);
}

inline ll query(int o,int l,int r,int x,int y)
{
	if (l>=x&&r<=y) return sum[o];
	pushdown(o);
	int mid=(l+r)>>1;ll res=0;
	if (x<=mid) res=pls(res,query(o<<1,l,mid,x,y));
	if (y>mid) res=pls(res,query(o<<1|1,mid+1,r,x,y));
	return res;
}

int main()
{
	n=rd();
	for (int i=1;i<=n;i++) num[i]=rd();
	for (int i=1;i<=n;i++) cnt[num[i]]++;
	for (int i=n-1;i;i--) cnt[i]+=cnt[i+1];
	ll all=1;
	for (int i=n;i;i--) all=all*(cnt[i]-n+i)%mod;
	if (!all) { puts("0");return 0; }
	for (int i=1;i<=n;i++) h[i]=pii(num[i],i);
	sort(h+1,h+n+1);
	build(1,1,n);
	ll ans=0;int lst=n;
	for (int i=n;i;i--)
	{
		int x=h[i].first,id=h[i].second;
		ans=pls(ans,getsum(id-1)*all%mod);
		if (i<n) for (;lst>x;lst--) gao(1,ksm(cnt[lst]-n+lst,mod-2)%mod*(cnt[lst]-n+lst-1)%mod);
		if (id>1) ans=mns(ans,query(1,1,n,1,id-1)*inv2%mod);
		if (id<n) ans=pls(ans,query(1,1,n,id+1,n)*inv2%mod);
		modify(1,1,n,id,all);add(id);
	}
	printf("%lld\n",ans);
	return 0;
}