/* ***********************************************
Author        :dasinlsb
Created Time  :2018/6/12 18:23:43
File Name     :C:\dasin\mine.cpp
************************************************ */

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cassert>
#include<vector>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;
#define pb push_back
#define fi first
#define se second
#define SZ(x) ((int)((x).size()))
const int N=200005;
const int mod=1000*1000*1000+7;
int n,ans,a[N],g[N],f[N],T[N],S[N],rs[N];
int pw(int x,int y){
  int t=1;
  for(;y;y>>=1,x=(ll)x*x%mod){
    if(y&1)t=(ll)t*x%mod;
  }
  return t;
}
struct Node{
  int x,y;
  Node(){}Node(int _x,int _y){x=_x,y=_y;}
  Node operator*(Node t){return Node((ll)x*t.x%mod,y+t.y);}
  Node operator/(Node t){return Node((ll)x*pw(t.x,mod-2)%mod,y-t.y);}
}h[N];
void add(int a[],int x,int y){for(x=n-x+1;x<=n;x+=x&-x)a[x]=(a[x]+y)%mod;}
int ask(int a[],int x){int t=0;for(x=n-x+1;x>0;x-=x&-x)t=(t+a[x])%mod;return t;}
int main(){
 // freopen("C:/dasin/aa.in","r",stdin);
  //freopen("C:/dasin/mine.out","w",stdout);
  int i,j;
  scanf("%d",&n);
  for(i=1;i<=n;++i)scanf("%d",a+i);
  for(i=1;i<=n;++i)g[a[i]]++;
  for(i=n;i;--i)g[i]+=g[i+1];
  for(i=1;i<=n;++i){
    f[i]=g[i]-n+i;
    if(f[i]<1)return puts("0"),0;
    h[i]=f[i]==1?Node(1,1):Node((ll)(f[i]-1)*pw(f[i],mod-2)%mod,0);
  }
  rs[n]=n;
  for(i=n-1;i;--i)rs[i]=f[i+1]==1?i:rs[i+1];
  //for(i=1;i<=n;++i)printf("rs %d %d\n",i,rs[i]);
  for(i=2;i<=n;++i){
    h[i]=h[i]*h[i-1];
    //printf("pre h %d %d %d\n",i,h[i].x,h[i].y);
    //printf("h %d %d %d\n",i,h[i].x,h[i].y);
    f[i]=(ll)f[i]*f[i-1]%mod;
  }
  int inv2=pw(2,mod-2);
  for(j=i=n;i;--i){
    int res=(ll)f[n]*inv2%mod*(ask(T,a[i])-ask(T,rs[a[i]]+1)+mod)%mod*pw(h[a[i]].x,mod-2)%mod;
    //printf("%d %d %d %d\n",i,f[n],ask(a[i]),h[i].x);
    //printf("res1 %d %d\n",i,res);
    ans=(ans+res)%mod;
    add(T,a[i],h[a[i]].x);
  }
  for(i=1;i<=n;++i)T[i]=0;
  for(j=i=1;i<=n;++i){
    int res=((ll)f[n]*ask(S,a[i]+1)%mod-(ll)f[n]*inv2%mod*(ask(T,a[i]+1)-ask(T,rs[a[i]]+1)+mod)%mod*pw(h[a[i]].x,mod-2)%mod)%mod;
    ans=(ans+res)%mod;
    add(T,a[i],h[a[i]].x);
    add(S,a[i],1);
  }
  if(ans<0)ans+=mod;
  printf("%d\n",ans);
  return 0;
}
