n,k = map(int,raw_input().split()) a = map(int,raw_input().split()) b = [sorted(a).index(i) for i in a] cnt = 0 for i in range(n): if b[i]%k != i%k: cnt = -1 if cnt == 0: for i in range(n): j = b.index(i) c = cmp(i,j) cnt += abs(i-j)/k while i != j: b[j], b[j+k*c] = b[j+k*c], b[j] j = j+k*c print cnt