bit = [0] * 220000 def add(x): x += 1 while x < len(bit): bit[x] += 1 x += x & -x def getSum(x): x += 1 ans = 0 while x > 0: ans += bit[x] x -= x & -x return ans N, M = map(int, input().split()) P = list(map(int, input().split())) r = 0 for p in P[::-1]: r += getSum(p) add(p) ans = r // M * M for _ in range(6): if ans >= r and ans % 2 == r % 2: print(ans) exit() ans += M print(-1)