N,K=map(int,input().split()) A=list(map(int,input().split())) B=[] for i in range(N): B.append((A[i],i)) list.sort(B) ok=True for i in range(N): if B[i][1]%K!=i%K: ok=False if not ok: print(-1) exit() def bubble(x): res=0 for i in range(len(x)): for j in range(len(x)-1): if x[j]>x[j+1]: x[j],x[j+1]=x[j+1],x[j] res+=1 return res ans=0 for i in range(K): ans+=bubble(A[i::K]) print(ans)