import sys n, k = [int(i) for i in input().split()] a = list(map(int, input().split())) b = sorted(a) location_a = {} for i in range(n): location_a[b[i]] = i ans = 0 for i in range(k): l = [] j = i while j < n: l.append(j) j += k sz = len(l) visited = [False]*sz for j in range(sz): if visited[j]: continue c = 0 d = j while not visited[d]: visited[d] = True location_b = location_a[a[l[d]]] if location_b % k != i: print(-1) sys.exit() d = (location_b - i)//k c += 1 if c > 1: ans += c - 1 print(ans)