def sort_counter(lis): count = 0 while True: innner_counter = 0 for i in range(len(lis) - 1): if lis[i] > lis[i + 1]: lis[i], lis[i + 1] = lis[i + 1], lis[i] innner_counter += 1 if innner_counter == 0: break else: count += innner_counter return count N, K = map(int, input().split(' ')) g = [[] for i in range(K)] for i, n in enumerate(map(int, input().split(' '))): g[i % K].append(n) flag = True if N < K: flag = False for n in zip(*list(map(lambda l: sorted(l), g))): tn = n[0] for ttn in n[1:]: if tn <= ttn: tn = ttn continue flag = False break if flag == False: break if flag: count = 0 for l in g: count += sort_counter(l) print(count) else: print(-1)