from copy import deepcopy N, K = map(int, input().split()) A = list(map(int, input().split())) B = sorted(list(set(A))) D = dict(zip(B,range(len(B)))) for i in range(N): A[i] = D[A[i]] B = [[] for _ in range(K)] for i in range(N): B[i % K].append(A[i]) C = deepcopy(B) for b in B: b.sort() now = 0 for i in range(N): b = B[i%K][i//K] if now > b: print(-1) exit() now = b from atcoder.fenwicktree import FenwickTree ans = 0 for cs in C: if cs: NC = max(cs) ft = FenwickTree(NC + 1) cnt = 0 for c in cs: cnt += ft.sum(c, NC + 1) ft.add(c, 1) ans += cnt print(ans)