class fenwick_tree: def __init__(self, N): self.n = N self.data = [0] * N def add(self, p, x): assert 0 <= p < self.n p += 1 while p <= self.n: self.data[p - 1] += x p += p & -p def sum(self, l, r): """return sum(a[l:r-1])""" assert 0 <= l and l <= r and r <= self.n return self._sum(r) - self._sum(l) def _sum(self, r): s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s n, m = map(int, input().split()) p = list(map(int, input().split())) ft = fenwick_tree(n) l = 0 for i in range(n): l += ft.sum(p[i], n) ft.add(p[i] - 1, 1) if l % 2 == 1 and m % 2 == 0: print(-1) else: ans = 0 - -l // m * m if ans % 2 != l % 2: ans += m print(ans)