N,K=map(int,raw_input().split()) a=map(int,raw_input().split()) A=[(a[i],i) for i in range(N)] A.sort() for i,(p,q) in enumerate(A): if N<=K and i!=q: print -1 exit() a[q]=i ans=0 for i in range(K): for j in range(i,N,K): for k in range(j+K, N, K): if a[j]%K != i or a[k]%K !=i: print -1 exit() elif a[j]>a[k]: ans += 1 print ans