#include <bits/stdc++.h>

using namespace std;

#define X first
#define Y second
#define mp make_pair
#define pb push_back
#define Debug(...) fprintf(stderr, __VA_ARGS__)

typedef long long LL;
typedef long double LD;
typedef unsigned int uint;
typedef pair <int, int> pii;
typedef unsigned long long uLL;

template <typename T> inline void Read(T &x) {
  char c = getchar();
  bool f = false;
  for (x = 0; !isdigit(c); c = getchar()) {
    if (c == '-') {
      f = true;
    }
  }
  for (; isdigit(c); c = getchar()) {
    x = x * 10 + c - '0';
  }
  if (f) {
    x = -x;
  }
}

template <typename T> inline bool CheckMax(T &a, const T &b) {
  return a < b ? a = b, true : false;
}

template <typename T> inline bool CheckMin(T &a, const T &b) {
  return a > b ? a = b, true : false;
}

const int N = 200005;
const int mod = 1e9 + 7;

int n, s, ans, sub, a[N], d[N], bit[N], cnt[N], lst[N];

inline int Qow(int x, int y) {
  int r = 1;
  for (; y; y >>= 1, x = 1LL * x * x % mod) {
    if (y & 1) {
      r = 1LL * r * x % mod;
    }
  }
  return r;
}

inline void Modify(int x, int v) {
  for (; x <= n; x += x & -x) {
    bit[x] = (bit[x] + v) % mod;
  }
}

inline int Query(int x) {
  int r = 0;
  for (; x; x -= x & -x) {
    r = (r + bit[x]) % mod;
  }
  return r;
}

int main() {
#ifdef wxh010910
  freopen("d.in", "r", stdin);
#endif
  Read(n), s = 1;
  for (int i = 1; i <= n; ++i) {
    Read(a[i]), ++cnt[a[i]];
  }
  for (int i = n; i; --i) {
    cnt[i] = (cnt[i] + cnt[i + 1]) % mod;
  }
  for (int i = 1; i <= n; ++i) {
    cnt[i] -= n - i;
    if (cnt[i] <= 0) {
      puts("0");
      return 0;
    }
    s = 1LL * s * cnt[i] % mod;
    if (cnt[i] > 1) {
      d[i] = 1LL * (cnt[i] - 1) * Qow(cnt[i], mod - 2) % mod;
      if (d[i - 1]) {
        d[i] = 1LL * d[i] * d[i - 1] % mod;
      }
      lst[i] = lst[i - 1];
    } else {
      lst[i] = i;
    }
  }
  memset(bit, 0, sizeof bit);
  for (int i = 1; i <= n; ++i) {
    ans = (1LL * s * (Query(a[i]) - Query(lst[a[i]]) + mod) % mod * d[a[i]] + ans) % mod;
    Modify(a[i], Qow(d[a[i]], mod - 2));
  }
  ans = 1LL * ans * (mod + 1 >> 1) % mod;
  memset(bit, 0, sizeof bit);
  for (int i = 1; i <= n; ++i) {
    ans = (1LL * s * (i - 1 - Query(a[i])) + ans) % mod;
    Modify(a[i], 1);
  }
  memset(bit, 0, sizeof bit);
  for (int i = n; i; --i) {
    if (d[a[i]]) {
      sub = (1LL * s * (Query(a[i] - 1) - Query(lst[a[i]]) + mod) % mod * d[a[i]] + sub) % mod;
      Modify(a[i], Qow(d[a[i]], mod - 2));
    }
  }
  sub = 1LL * sub * (mod + 1 >> 1) % mod;
  printf("%d\n", (ans - sub + mod) % mod);
#ifdef wxh010910
  Debug("My Time: %.3lfms\n", (double)clock() / CLOCKS_PER_SEC);
#endif
  return 0;
}
