n, m = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = [(a - b) % m for a, b in zip(A, B)] b = 0 D = [] for c in C: D.append((c - b) % m) b = c D.append((-b) % m) D.sort() tot = sum(D) tot2 = 0 ans = tot for d in D[::-1]: tot2 += m - d tot -= d ans = min(ans, max(tot, tot2)) print(ans)