class Fenwick_Tree: def __init__(self, n): self.n = n self.data = [0] * n def add(self, p, x): p += 1 while p <= self.n: self.data[p - 1] += x p += p & -p def sum(self, l, r): '''範囲[l, r)(lからr-1まで)の総和を求める''' return self._sum(r) - self._sum(l) def _sum(self, r): '''範囲[0, r)(0からr-1まで)の総和を求める''' s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s n, m = map(int, input().split()) A = list(map(int, input().split())) cnt = 0 FT = Fenwick_Tree(n) for i in range(n): a = A[i] - 1 cnt += FT.sum(a, n) FT.add(a, 1) if cnt % 2 == 1 and m % 2 == 0: print(-1) elif cnt % m == 0: print(cnt) else: r = m - cnt % m if r % 2 == 0: print(cnt + r) else: print(cnt + r + m)