n, k = map(int, input().split()) A = list(map(int, input().split())) ans = 0 for s in range(k): g = s while g < n: g += k for i in range(s, g, k): for j in range(g - k, i, -k): if A[j] < A[j - k]: A[j - k], A[j] = A[j], A[j - k] ans += 1 if A != sorted(A): print(-1) else: print(ans)