from collections import deque def solve(n: int, k: int, a: list[int]) -> None: if sum(a) % k: print(-1) return dq: deque[int] = deque() threshold = k * (k - 1) // 2 for i in range(n): q = (max(0, a[i] - threshold) + (k - 1)) // k a[i] -= q * k # O(n log n), but can be optimized to O(k^2) by using bucket sort a.sort(reverse=True) dq.append(a[0]) next_push = 1 INF = 1 << 30 ans = INF t = sum(a) // k while True: e = dq.popleft() if e <= t: ans = t e -= k if e < 0: break while next_push < n and a[next_push] >= e: dq.append(a[next_push]) next_push += 1 dq.append(e) t -= 1 if ans == INF: print(-1) else: print(ans) t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) solve(n, k, a)