import sys sys.setrecursionlimit(5*10**5) input = sys.stdin.readline from collections import defaultdict, deque, Counter from heapq import heappop, heappush from bisect import bisect_left, bisect_right from math import gcd def add(x, y): return x + y def e(a): if a == min: return 10**18 if a == max: return -10**18 if a == add: return 0 class SegTree: def __init__(self, segf, init_val): n = len(init_val) self.segf = segf self.e = e(segf) self.seg_len = 1 << n.bit_length() self.seg = [self.e] * 2*self.seg_len for i in range(n): self.seg[i + self.seg_len] = init_val[i] for i in range(self.seg_len)[::-1]: self.seg[i] = segf(self.seg[i << 1], self.seg[i << 1 | 1]) def point_add(self, pos, x): pos += self.seg_len self.seg[pos] += x while True: pos >>= 1 if not pos: break self.seg[pos] = self.segf( self.seg[pos << 1], self.seg[pos << 1 | 1]) def point_update(self, pos, x): pos += self.seg_len self.seg[pos] = x while True: pos >>= 1 if not pos: break self.seg[pos] = self.segf( self.seg[pos << 1], self.seg[pos << 1 | 1]) def get_range(self, l, r): l += self.seg_len r += self.seg_len res = self.e while l < r: if l & 1: res = self.segf(res, self.seg[l]) l += 1 if r & 1: r -= 1 res = self.segf(res, self.seg[r]) l >>= 1 r >>= 1 return res # ------ range_add & get_point ------- def range_add(self, l, r, x): l += self.seg_len r += self.seg_len self.seg[l] += x self.seg[r] += x while l < r: if l & 1: self.seg[l] = self.segf(x, self.seg[l]) l += 1 if r & 1: r -= 1 self.seg[r] = self.segf(x, self.seg[r]) l >>= 1 r >>= 1 def get_point(self, pos): pos += self.seg_len res = self.seg[pos] while True: pos >>= 1 if not pos: break res = self.segf(res, self.seg[pos]) return res n,m = map(int,input().split()) p = list(map(int,input().split())) st = SegTree(add,[0]*(n+10)) ans = 0 for i in range(n): ans += st.get_range(p[i],n+5) st.point_add(p[i],1) if ans == 0: print(0) elif m % 2 == 0 and ans % 2 == 1: print(-1) else: mn = m * (ans+m-1)//m if (mn - ans) % 2 == 0: print(mn) else: print(mn + m)