import sys import heapq input = sys.stdin.readline def read_values(): return tuple(map(int, input().split())) def read_list(): return list(map(int, input().split())) def main(): n,m=read_values() a=read_list() b=read_list() q=[] bef=0 r=0 for aa,bb in zip(a,b): add=(bb-aa-bef)%m bef=bb-aa r+=add heapq.heappush(q,-add) sum=r while r>=m: v = -heapq.heappop(q) sum+=m-v*2 r-=m ans=sum+r v = -heapq.heappop(q) sum+=m-v*2 r=m-r ans=min(ans,sum+r) print(ans//2) if __name__ == "__main__": main()