m, k = map(int, input().split()) A = list(map(int, input().split())) ans = 0 cnt = [0] * m left = 0 right = 0 plus = [0] * m mi_cnt = [0] * m pm = [0] * m for i, a in enumerate(A): c = cnt[a] * m + a ans += abs(c - i) cnt[a] += 1 if i <= c: left += 1 else: right += 1 l = c // m * m r = (c + m) // m * m if i <= l: plus[a] -= m elif i >= r: plus[a] += m else: mi_cnt[a] += 1 plus[a] += (i - l) - (r - i) tmp = (i - a) % m pm[tmp] += 1 tot = ans for i in range(1, m): tot += left - right + plus[m - i] left += -mi_cnt[m - i] + pm[i] right += mi_cnt[m - i] - pm[i] ans = min(ans, tot) print(ans // 2)