N=int(input()) M=[] for _ in range(N):M.append(int(input())) MAX=1<0:total+=M[i] cost=max(0,M[to]-(total%1000)) dp[s][to]=min(dp[s][to],dp[bs][frm]+cost) ans=min(dp[-1]) print(ans)