#include<bits/stdc++.h>
#define L long long
#define pi pair<int,int>
#define pii pair<int,pi>
#define aa first
#define bb second
#define xx aa
#define yy bb.aa
#define zz bb.bb
#define pb push_back
#define mp make_pair
using namespace std;
const int q=1000000007;
int n,a[200010],p,r=1;
vector<int> x[200010];
pi u=mp(1,0);
pii f[200010];
inline void operator+=(pii &a,pii &b)
{
	if(a.zz<u.bb)
	  {
	   a.yy=0;
	   a.zz=u.bb;
	  }
	if(b.zz<u.bb)
	  {
	   b.yy=0;
	   b.zz=u.bb;
	  }
	a.xx+=b.xx;
	a.yy=(a.yy+b.yy)%q;
}
inline int power(int a,int b)
{
	if(!b)
	  return 1;
	int c=power(a,b>>1);
	c=(L)c*c%q;
	if(b&1)
	  c=(L)c*a%q;
	return c;
}
inline pii sum(int i)
{
	pii k={};
	for(;i;i^=i&-i)
	  k+=f[i];
	return k;
}
inline void add(int i,pii k)
{
	for(;i<=n;i+=i&-i)
	  f[i]+=k;
}
int main()
{
	//freopen("E.in","r",stdin);
	//freopen("E.out","w",stdout);
	int i,j,k;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
	  {
	   scanf("%d",&a[i]);
	   x[a[i]].pb(i);
	  }
	for(i=n,k=1;i>0;i--)
	  {
	   k--;
	   j=x[i].size();
	   p=(p+((L)j*(j-1)/2+(L)j*k)%q*500000004)%q;
	   k+=j;
	   for(auto l:x[i])
	     {
	      pii w=sum(l-1);
	      p=(p+w.xx-(L)w.yy*u.aa)%q;
	     }
	   for(auto l:x[i])
	     add(l,mp(1,mp(power(u.aa,q-2),u.bb)));
	   if(k!=1)
	     u.aa=(L)u.aa*(1-power(k,q-2))%q;
	   else
	     u.bb++;
	   r=(L)r*k%q;
 	  }
 	p=(L)p*r%q;
 	p=(p+q)%q;
 	printf("%d\n",p);
	return 0;
}
