#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int N=1e6;
const int mo=1e9+7;
int Sum(int x,int y) {
    x+=y;
    return (x>=mo)?x-mo:x;
}
int Sub(int x,int y) {
    x-=y;
    return (x<0)?x+mo:x;
}
int Mul(int x,int y) {
    return (long long)x*y%mo;
}
int Pow(int x,int y=mo-2) {
    int z=1;
    while (y) {
        if (y&1) z=Mul(z,x);
        y>>=1;
        x=Mul(x,x);
    }
    return z;
}
int n,vx;
int a[N+10],v[N+10],g[N+10],h1[N+10],h2[N+10],nxt[N+10],lst[N+10];
struct bit {
    int t[N+10];
    void Add(int x,int va) {
        while (x<=N) {
            t[x]=Sum(t[x],va);
            x+=x&(-x);
        }
    }
    int Query(int x) {
        int sum=0;
        while (x) {
            sum=Sum(sum,t[x]);
            x-=x&(-x);
        }
        return sum;
    }
}bit1,bit2,bit3;
int Solve() {
    int ans=0;
    for (int i=1;i<=n;i++) {
        int lx=nxt[a[i]],rx=a[i];
        int sum=Mul(h2[a[i]+1],Sub(bit1.Query(rx),bit1.Query(lx-1)));
        ans=Sum(ans,Mul(sum,(mo+1)/2));
        lx=a[i]+1;
        rx=lst[a[i]+1]-1;
        sum=Mul(h1[a[i]],Sub(bit2.Query(rx),bit2.Query(lx-1)));
        ans=Sum(ans,Sub(Mul(vx,Sub(bit3.Query(n),bit3.Query(lx-1))),Mul(sum,(mo+1)/2)));
        bit1.Add(a[i],h1[a[i]]);
        bit2.Add(a[i],h2[a[i]+1]);
        bit3.Add(a[i],1);
    }
    return ans;
}
int main() {
    scanf("%d",&n);
    for (int i=1;i<=n;i++) {
        scanf("%d",&a[i]);
        v[a[i]]++;
    }
    for (int i=n-1;i>=1;i--) v[i]+=v[i+1]-1;
    vx=1;
    for (int i=1;i<=n;i++)
        vx=Mul(vx,v[i]);
    if (vx==0) {
        printf("0\n");
        return 0;
    }
    int now=1;
    for (int i=1;i<=n;i++) {
        if (v[i]==1) now=i;
        nxt[i]=now;
    }
    now=n+1;
    lst[n+1]=n+1;
    for (int i=n;i>=1;i--) {
        if (v[i]==1) now=i;
        lst[i]=now;
    }
    g[0]=1;
    for (int i=1;i<=n;i++)
        g[i]=Mul(g[i-1],max(v[i]-1,1));
    h1[0]=1;
    for (int i=1;i<=n;i++) h1[i]=Mul(h1[i-1],v[i]);
    h2[n+1]=1;
    for (int i=n;i>=1;i--) h2[i]=Mul(h2[i+1],v[i]);
    for (int i=1;i<=n+1;i++) {
        h1[i]=Mul(h1[i],Pow(g[i]));
        h2[i]=Mul(h2[i],g[i-1]);
    }
    int ans=Solve();
    printf("%d\n",ans);
    return 0;
}
