#include <bits/stdc++.h>
using namespace std;
int a[200005], cnt[200005], n, ans;
int val0[200005], val1[200005], t[200005];
int invval1[200005], nxt[200005], pre[200005];
int power(int x, int y) {
  int s = 1;
  for (; y; y /= 2, x = 1ll * x * x % 1000000007)
    if (y & 1) s = 1ll * s * x % 1000000007;
  return s;
}
void add(int x, int y) {
  for (; x <= n; x += x & (-x)) t[x] = (t[x] + y) % 1000000007;
}
int ask(int x) {
  int s = 0;
  for (; x; x -= x & (-x)) s = (s + t[x]) % 1000000007;
  return s;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]), cnt[a[i]]++;
  for (int i = n - 1; i; i--) cnt[i] += cnt[i + 1] - 1;
  for (int i = n; i; i--)
    if (cnt[i] <= 0) return puts("0"), 0;
  val0[0] = val1[0] = 1;
  for (int i = 1; i <= n; i++) {
    val0[i] = 1ll * val0[i - 1] * cnt[i] % 1000000007;
    val1[i] = 1ll * val1[i - 1] * max(cnt[i] - 1, 1) % 1000000007;
  }
  for (int i = 1; i <= n; i++) {
    val1[i] = 1ll * val1[i] * power(val0[i], 1000000007 - 2) % 1000000007;
    invval1[i] = power(val1[i], 1000000007 - 2);
  }
  nxt[n] = n;
  for (int i = n - 1; i; i--) nxt[i] = (cnt[i + 1] == 1 ? i : nxt[i + 1]);
  for (int i = n; i; i--) {
    int tmp = (ask(nxt[a[i]]) + 1000000007 - ask(a[i] - 1)) % 1000000007;
    ans = (ans + 1ll * tmp * invval1[a[i]] % 1000000007) % 1000000007;
    add(a[i], val1[a[i]]);
  }
  memset(t, 0, sizeof(t));
  pre[1] = 1;
  for (int i = 2; i <= n; i++) pre[i] = (cnt[i - 1] == 1 ? i : pre[i - 1]);
  for (int i = n; i; i--) {
    int tmp = (ask(a[i] - 1) + 1000000007 - ask(pre[a[i]] - 1)) % 1000000007;
    ans = (ans + 1000000007 - 1ll * tmp * val1[a[i]] % 1000000007) % 1000000007;
    add(a[i], invval1[a[i]]);
  }
  ans = 1ll * ans * power(2, 1000000007 - 2) % 1000000007;
  memset(t, 0, sizeof(t));
  for (int i = n; i; i--) {
    ans = (ans + ask(a[i] - 1)) % 1000000007;
    add(a[i], 1);
  }
  printf("%d", 1ll * ans * val0[n] % 1000000007);
}
