def bitadd(a,w,bit): #aにwを加える(1-origin) x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): #ind 1~aまでの和を求める ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret N,M = map(int,input().split()) BIT = [0] * (N+1) a = list(map(int,input().split())) ans = 0 for i in range(N): ans += i - bitsum(a[i],BIT) bitadd(a[i],1,BIT) if ans % M == 0: print (ans) elif M % 2 == 0 and ans % 2 == 1: print (-1) else: now = ans // M * M while (True): if now >= ans and (now-ans) % 2 == 0: print (now) break now += M