#include using namespace std; using i64 = int64_t; constexpr i64 mod = 998244353; i64 power(i64 a, i64 r) { i64 res = 1; for (; r; r >>= 1, a = a * a % mod) { if (r & 1) { res = res * a % mod; } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); i64 n, m; cin >> n >> m; i64 ans = 0; vector bit(n + 1); for (int i = 1, p; i <= n; i += 1) { cin >> p; ans += i - 1; for (int x = p; x; x -= x & -x) { ans -= bit[x]; } for (int x = p; x <= n; x += x & -x) { bit[x] += 1; } } i64 k = (ans + m - 1) / m * m; if ((k - ans) % 2 == 0) { cout << k; } else if ((k + m - ans) % 2 == 0) { cout << k + m; } else { cout << -1; } }