#include <bits/stdc++.h>
const int N = 201000, MOD = 1000000007;
long long inv(int x) { return x == 1 ? 1 : (-(MOD / x) * inv(MOD % x) % MOD); }
struct bit {
  int w[N];
  inline void reset() { memset(w, 0, sizeof(w)); }
  inline int lowbit(int x) { return x & (-x); }
  void inc(int p, int x) {
    for (; p < N; p += lowbit(p)) w[p] = (w[p] + x) % MOD;
  }
  int ask(int p) {
    int ret = 0;
    for (; p; p -= lowbit(p)) ret = (ret + w[p]) % MOD;
    return ret;
  }
} T;
namespace calculator {
int cnt[N], D[N], bel[N];
int *A, n;
bool judge(int *A_, int n_) {
  A = A_, n = n_;
  memset(cnt, 0, sizeof(cnt));
  for (int i = 1; i < n; i++) cnt[i] = -1;
  for (int i = 1; i <= n; i++) cnt[A[i]]++;
  for (int i = n; i; i--) cnt[i - 1] += cnt[i];
  for (int i = 1; i <= n; i++)
    if (cnt[i] < 1) return 0;
  return 1;
}
int solve(int *A_, int n_) {
  if (!judge(A_, n_)) return 0;
  int ret = 0, S = 1;
  for (int i = 1; i <= n; i++) S = (long long)S * cnt[i] % MOD;
  for (int i = 1, j; i <= n; i = j + 1) {
    for (j = i; j < n && cnt[j + 1] != 1; j++)
      ;
    for (int k = i; k <= j; k++) bel[k] = i;
    D[i] = 1;
    for (int k = i + 1; k <= j; k++)
      D[k] = (long long)D[k - 1] * (cnt[k] - 1) % MOD * inv(cnt[k]) % MOD;
  }
  T.reset();
  for (int i = 1, x, y, z; i <= n; i++) {
    x = A[i] - 1, y = bel[A[i]], z = (T.ask(x) - T.ask(y - 1)) % MOD;
    ret = (ret + (long long)z * D[A[i]] % MOD * S % MOD);
    T.inc(A[i], inv((D[A[i]]) + MOD) % MOD);
  }
  ret = (ret + MOD) % MOD;
  return ret * inv(2) % MOD;
}
}  // namespace calculator
int A[N], cnt[N];
int n, S, ans;
int fuck() {
  T.reset();
  int ret = 0;
  for (int i = 1; i <= n; i++)
    ret = (ret + T.ask(n) - T.ask(A[i])) % MOD, T.inc(A[i], 1);
  return ret;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", A + i);
  if (!calculator::judge(A, n)) {
    printf("0\n");
    return 0;
  }
  for (int i = S = 1; i <= n; i++) S = (long long)S * calculator::cnt[i] % MOD;
  ans = 0;
  for (int i = 1; i <= n; i++) ans = (ans + cnt[A[i]]) % MOD, cnt[A[i]]++;
  ans = (long long)ans * S % MOD * inv(2) % MOD;
  ans = (ans + calculator::solve(A, n)) % MOD;
  ans = (ans + (long long)S * fuck()) % MOD;
  std::reverse(A + 1, A + n + 1);
  ans = (ans - calculator::solve(A, n)) % MOD;
  ans = (ans + MOD) % MOD;
  printf("%d\n", ans);
  return 0;
}
