#include<bits/stdc++.h>
#define rep(i,x,y) for (int i=(x);i<=(y);i++)
#define per(i,x,y) for (int i=(x);i>=(y);i--)
#define ll long long
#define inf 1000000001
using namespace std;
int read(){
	char ch=getchar();int x=0,op=1;
	for (;!isdigit(ch);ch=getchar()) if (ch=='-') op=-1;
	for (;isdigit(ch);ch=getchar()) x=(x<<1)+(x<<3)+ch-'0';
	return x*op;
}
#define N 200005
#define mod 1000000007
#define inv2 500000004
int n,a[N],cnt[N],val0[N],val1[N],val2[N],val3[N],pos[N],ans;
int ksm(int x,int p){
	int ret=1;
	for (;p;p>>=1,x=(ll)x*x%mod) if (p&1) ret=(ll)ret*x%mod;
	return ret;
}
int getinv(int x){return ksm(x,mod-2);}
void upd(int &x,int y){x+=y;x-=x>=mod?mod:0;}
struct bit{
	int t[N];
	void clr(){memset(t,0,sizeof(t));}
	void add(int x,int val){
		for (int i=x;i<=n;i+=i&-i) upd(t[i],val);
	}
	int qry(int x){
		int ret=0;
		for (int i=x;i;i-=i&-i) upd(ret,t[i]);
		return ret;
	}
}tr;
int main(){
	n=read();
	rep (i,1,n) cnt[a[i]=read()]++;
	per (i,n-1,1) cnt[i]+=cnt[i+1]-1;
	rep (i,1,n) if (cnt[i]<=0){puts("0");exit(0);}
	val0[0]=val1[0]=1;
	rep (i,1,n){
		val0[i]=(ll)val0[i-1]*cnt[i]%mod;
		val1[i]=(ll)val1[i-1]*max(cnt[i]-1,1)%mod;
		val2[i]=(ll)val0[i]*getinv(val1[i])%mod;
		val3[i]=(ll)val1[i]*getinv(val0[i])%mod;
	}
	tr.clr();
	pos[n]=n;
	per (i,n-1,1) pos[i]=cnt[i+1]==1?i:pos[i+1];
	per (i,n,1){
		int val=(tr.qry(pos[a[i]])+mod-tr.qry(a[i]-1))%mod;
		upd(ans,(ll)val*val2[a[i]]%mod);
		tr.add(a[i],val3[a[i]]);
	}
	tr.clr();
	pos[1]=1;
	rep (i,2,n) pos[i]=cnt[i]==1?i:pos[i-1];
	per (i,n,1){
		int val=(tr.qry(a[i]-1)+mod-tr.qry(pos[a[i]]-1))%mod;
		upd(ans,(mod-(ll)val*val3[a[i]]%mod)%mod);
		tr.add(a[i],val2[a[i]]);
	}
	ans=(ll)ans*inv2%mod;
	tr.clr();
	per (i,n,1){
		upd(ans,tr.qry(a[i]-1));
		tr.add(a[i],1);
	}
	ans=(ll)ans*val0[n]%mod;
	cout<<ans<<'\n';
	return 0;
}