Problem:
 Score: 200 points    Problem Statement  Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i -th section from the left has a length of A_i millimeters.  Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:   Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).  Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.   Find the minimum amount of money needed before cutting the bar into two parts with the same length.      Constraints   2 \leq N \leq 200000  1 \leq A_i \leq 2020202020  All values in input are integers.         Input  Input is given from Standard Input in the following format:  N  A_1  A_2  A_3  ...  A_N       Output  Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.        Sample Input 1 3
2 4 3      Sample Output 1 3  The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:   Shrink the second section from the left. The lengths of the sections are now [2, 3, 3] .  Shrink the first section from the left. The lengths of the sections are now [1, 3, 3] .  Shrink the second section from the left. The lengths of the sections are now [1, 2, 3] , and we can cut the bar at the second notch from the left into two parts of length 3 each.        Sample Input 2 12
100 104 102 105 103 103 101 105 104 102 104 101      Sample Output 2 0

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
sum=[0]*(len(a)+1)
for i in range(len(a)):
    sum[i+1]=sum[i]+a[i]


mini=2020202020
for i in range(len(sum)):
    mini=min(mini, abs(sum[i] - (sum[-1] - sum[i])))

print(mini)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
hoge = [0] * n
cnt = 0
for i in range(n):
    
    cnt += a[i]
    hoge[i] = cnt
hoge_ = [0] * n
cnt = 0
for i in range(n - 1, -1, -1):
    cnt += a[i]
    hoge_[i] = cnt
ans = float('Inf')
for i in range(n - 1):
    ans = min(ans, abs(hoge[i] - hoge_[i + 1]))
print(ans)

Solution (Python):
n = int(input())

a = list(map(int, input().split()))

cnt = 0
ave = sum(a)/2

for i in range(n):
    cnt += a[i]
    if cnt >= ave:
        ans = min(cnt*2-ave*2, ave*2-(cnt-a[i])*2)
        break

print(int(ans))

Solution (Python):
import sys

n = int(input())

a = list(map(int, input().split()))

cnt = 0
ave = sum(a)/2

for i in range(n):
    cnt += a[i]
    if cnt == ave:
        print(0)
        sys.exit()
    
    elif cnt > ave:
        x = ave -cnt +a[i]
        if x >= cnt -ave:
            x = cnt -ave
        break

print(int(x*2))

Solution (Python):
n = int(input())
a = list(map(int, input().split())) 

x = [0]
aaa = 0
aa = sum(a)

for i in range(n):
    aaa += a[i]
    x.append(aaa)
    
    

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(aa - x[i]*2))

print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split())) 

x = [0]
aaa = 0
aa = sum(a)
y = [aa]
for i in range(n):
    aaa += a[i]
    x.append(aaa)
    aa -= a[i]
    y.append(aa)

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(x[i] - y[i]))

print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split())) 

x = [0]
aaa = 0
for i in range(n):
    aaa += a[i]
    x.append(aaa)
aa = sum(a)
y = [aa]
for i in range(n):
    aa -= a[i]
    y.append(aa)

ans = 202020202020
for i in range(n+1):
    ans = min(ans, abs(x[i] - y[i]))

print(ans)

Solution (Python):






N = int(input())
A = list(map(int, input().split()))





total = sum(A)
ans = total
left = 0
for i in A:
    left += i
    right = total - left
    ans = min(ans, abs(left - right))

print(ans)

Solution (Python):
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True




def warshall_floyd(d, n):
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d



def dijkstra_heap(s, edge, n):
    
    d = [10**20] * n
    used = [True] * n 
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d


def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr


def lcm(x, y):
    return (x * y) // gcd(x, y)


def lcm_list(numbers):
    return reduce(lcm, numbers, 1)


def gcd_list(numbers):
    return reduce(gcd, numbers)






def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P


def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret



n = int(input())    
a = list(map(int, input().split()))
total = sum(a)
cnt = 0
ans = 0
for i in range(n):
    cnt += a[i]
    if cnt == total / 2:
        break
    if cnt >= -(-total // 2):
        ans += a[i] - (abs(total - cnt - (cnt - a[i])))
        break
print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
right = sum(a)
left = 0
ans=10**20
for l in a:
  left+=l
  right-=l
  ans=min(ans,abs(left-right))
print(ans)

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
LEFT = A[0]
RIGHT = sum(A[1:])
MIN = abs(LEFT-RIGHT)
for i in range(1,N-1):
    LEFT += A[i]
    RIGHT -= A[i]
    MIN = min(MIN,abs(LEFT-RIGHT))
print(MIN)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
t = sum(a)
ans = sum(a)
l = 0
for i in a:
    l += i 
    r = t-l
    ans = min(ans, abs(l-r))
print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

ans = (2020202020)**100
sum_A = sum(A)
hoge = 0


for i in range(N-1):
  hoge = hoge + A[i]
  ans = min(ans,(abs(sum_A - (hoge*2))))

print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

ans = float('inf') 
sum_A = sum(A)
CumSum = 0


for i in range(N-1):
  CumSum = CumSum + A[i]
  ans = min(ans,(abs((sum_A - CumSum)-(CumSum))))

print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

ans = float('inf')
sum_A = sum(A)
hoge = 0


for i in range(N-1):
  hoge = hoge + A[i]
  ans = min(ans,abs(sum_A - (hoge*2)))

print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

left = a[0]
right = a[-1]
center = 0
sum_a = sum(a)
flg = False
for i in range(1, n-1):
    if left + a[i] > sum_a/2 and flg is False:
        flg = True
        center = a[i]
        right -= a[i]
    elif left + a[i] == sum_a / 2:
        print(0)
        exit()
    if flg is False:
        left += a[i]
    else:
        right += a[i]

print(abs(min(left+center-right, right+center-left)))

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
allL = sum(A)
L, mL = 0, float('inf')
for i in range(N):
    L += A[i]
    if abs(2*L-allL) < mL:
        mL = abs(2*L-allL)
    else:
        break
print(mL)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
nagasa = sum(a)
now = 0
for i in range(n):
    if now + a[i] < nagasa/2:
        now += a[i]
    elif now + a[i] == nagasa/2:
        print(0)
        exit()
    elif now + a[i] > nagasa/2:
        print(min(nagasa-2*now,2*(now+a[i])-nagasa))
        exit()

Solution (Python):
import itertools,numpy as np,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N = I()
A = LI()
sum_A = sum(A)
accumulate_A = np.array(list(itertools.accumulate(A)))
sub_A1 = sum_A-accumulate_A
sub_A2 = sum_A-sub_A1
print(np.abs(sub_A1-sub_A2).min())

Solution (Python):
import itertools,numpy as np,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N = I()
A = LI()
sum_A = sum(A)
accumulate_A = np.array(list(itertools.accumulate(A)))
sub_A1 = sum_A-accumulate_A
sub_A2 = sum_A-sub_A1
print(np.abs(sub_A1-sub_A2).min())

Solution (Python):
import itertools,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N = I()
A = LI()
ans = float('INF')
sum_A = sum(A)
accumulate_A = list(itertools.accumulate(A))
for i in range(N-1):
    ans = min(ans,abs(sum_A-accumulate_A[i]*2))
print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
total = sum(a)
total_a, total_b = 0, 0
i = 0
while total_a + a[i] <= total / 2:
    total_a += a[i]
    i += 1
i = n - 1
while total_b + a[i] <=  total / 2:
    total_b += a[i]
    i -= 1

print(total - max(total_a, total_b) * 2)

Solution (Python):
n = int(input())
as_ = list(map(int, input().strip().split()))

total_length = sum(as_)
current = 0
for a in as_:
    if current + a == total_length // 2:
        print(0)
        exit(0)
    if current + a > total_length / 2:
        candidate1 = current
        candidate2 = current + a
        break

    current += a

left1 = candidate1
right1 = total_length - left1
left2 = candidate2
right2 = total_length - left2


ans = min(
    right1 - left1, 
    left2 - right2 
)
print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

mid = sum(a)/2
cum = 0
diff = 10**10
for each in a:
  cum += each
  diff = min(diff, abs(mid-cum))
  
print(int(diff/0.5))

Solution (Python):
import numpy as np

n = int(input())
a = list(map(int, input().split()))

cum = np.cumsum(a)
mid = cum[-1]/2
diff = 10**10
for each in cum:
  diff = min(diff, abs(mid-each))
  
print(int(diff/0.5))

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
m = 10**10
x = sum(a)
y = 0
for i in range(n):
    x -= a[i]
    y += a[i]
    m = min(abs(x-y),m)
print(m)

Solution (Python):
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))

A_cs = A.cumsum()
A_cs = A_cs - A_cs[-1]/2
div = np.abs(A_cs).argmin()

print(abs(A[:div+1].sum() - A[div+1:].sum()))

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    from itertools import accumulate

    N = int(input())  
    A = list(map(int, input().split()))
    zenbu=sum(A)
    B = [0] + A
    B = list(accumulate(B))
    C = [zenbu]*(N+1)
    import numpy as np
    B=np.array(B)
    C=np.array(C)
    D=C-B
    ans=10**18
    for i in range(1, N):
        ans = min(abs(B[i]-D[i]),ans)
    print(ans)
resolve()

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    from itertools import accumulate

    N = int(input())  
    A = list(map(int, input().split()))
    zenbu=sum(A)
    B = [0] + A
    B = list(accumulate(B))  


    ans=10**18
    for i in range(1, N):
        ans = min(abs(B[i]-(zenbu-B[i])),ans)
    print(ans)

resolve()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    n = int(input())

    stick = list(map(int, input().split()))

    total = sum(stick)
    mid = total // 2

    cum = 0
    midi = 0
    for i, block in enumerate(stick):
        cum += block
        if cum >= mid:
            midi = i
            break

    l1 = cum
    r1 = total - l1
    diff1 = abs(l1 - r1)
    
    l2 = l1 - stick[midi]
    r2 = r1 + stick[midi]
    diff2 = abs(l2 - r2)
    
    print(min(diff1, diff2))

main()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    n = int(input())

    stick = list(map(int, input().split()))

    total = sum(stick)
    mid = total // 2

    cum = 0
    midi = 0
    for i, block in enumerate(stick):
        cum += block
        if cum >= mid:
            midi = i
            break

    l1 = sum(stick[:midi])
    r1 = sum(stick[midi:])
    diff1 = abs(l1 - r1)
    
    l2 = l1 + stick[midi]
    r2 = r1 - stick[midi]
    diff2 = abs(l2 - r2)
    
    print(min(diff1, diff2))

main()

Solution (Python):
n = int(input())

stick = list(map(int, input().split()))

total = sum(stick)
mid = total // 2

cum = 0
midi = 0
for i, block in enumerate(stick):
    cum += block
    if cum >= mid:
        midi = i
        break

l1 = sum(stick[:midi])
r1 = sum(stick[midi:])
diff1 = abs(l1 - r1)
 
l2 = l1 + stick[midi]
r2 = r1 - stick[midi]
diff2 = abs(l2 - r2)
 
print(min(diff1, diff2))

Solution (Python):
n = int(input())

stick = list(map(int, input().split()))

total = sum(stick)
mid = total // 2

cum = 0
midi = 0
for i, block in enumerate(stick):
    cum += block
    if cum >= mid:
        midi = i
        break

l1 = stick[:midi]
r1 = stick[midi:]
diff1 = abs(sum(l1) - sum(r1))
 
l2 = stick[:midi+1]
r2 = stick[midi+1:]
diff2 = abs(sum(l2) - sum(r2))
 
print(min(diff1, diff2))

Solution (Python):
import sys
import numpy as np

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = list(map(int, input().split()))
    cumsum = np.cumsum(A)
    half = sum(A) // 2

    ans = INF
    for i in range(N - 1):
        left = cumsum[i]
        right = cumsum[-1] - cumsum[i]
        cost = abs(half - left) + abs(right - half)
        if cost < ans:
            ans = cost

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
L = sum(a)
l = 0
i = 0
while l < L / 2:
    l += a[i]
    i += 1
print(min(abs(sum(a[:i - 1]) - sum(a[i - 1:])), abs(sum(a[:i]) - sum(a[i:]))))

Solution (Python):
n = int(input())
A = list(map(int,input().split()))
s = [0]

for i in A:
    s.append(i+s[-1])

M = 10000000000

for i in range(1,len(s)-1):
    dif = abs((s[-1]-s[i]) - s[i])
    M = min(M,dif)

print(M)

Solution (Python):
n = int(input())
arr = list(map(int,input().split()))

tot = sum(arr)

temp = 0
ans = 1e18
for i in range(n):
    temp += arr[i]
    rest = tot-temp
    cost = abs(rest-temp)
    if cost < ans:
        ans = cost

print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
barlen = 0
for x in a:
  barlen += x
halflen = barlen/2
curbarlen = 0
minhalfdis = barlen
for i in range(n):
  curbarlen += a[i]
  minhalfdis = min(minhalfdis,abs(halflen-curbarlen))
print(int(minhalfdis*2))

Solution (Python):
A=int(input())
l=list(map(int,input().split()))
right=l[0]
left=sum(l[1:])
ans=left-right
for i in range(A-2):
    right+=l[i+1]
    left-=l[i+1]
    ans=min(ans,abs(right-left))
print(ans)

Solution (Python):
'''
参考
https://qiita.com/c-yan/items/f7c99c8f8ec418a58c42

棒の全長をL、切断箇所をCとすると、かかるコストは|2C-L|となる
（左端から切断箇所までの長さを2倍し、元の棒の全長を引いたものの絶対値）
∵
・CがL/2よりも左にある場合（=棒の左端からCまでの長さのほうが短い）
⇒Cよりも左側に2C-L足すか、右側を2C-L減らす
・CがL/2よりも右にある場合（=棒の左端からCまでの長さのほうが長い）
⇒Cよりも左側を2C-L減らすか、右側に2C-L足す

与えられたリストAのうち、どの地点をCとするかは
リストAの先頭の要素からN-1個の要素をそれぞれ調べ、
先頭要素から現在の要素までの合計（累積和）を格納するリストを別途作成、
そのリストに対して|2C-L|が最小となるケースを調べる
'''
N = int(input())
A = list(map(int, input().split()))
L = sum(A)

tmp = A[:-1]

for i in range(1, N-1):

    tmp[i] += tmp[i-1]

cost = min(abs(c*2-L) for c in tmp)
print(cost)

Solution (Python):
def main():
    N=int(input())
    A=[int(_) for _ in input().split()]
    left=0
    right=sum(A)
    ans=right
    for i in range(N):
        left+=A[i]
        right-=A[i]
        ans = min(ans, abs(left-right))
    print(ans)

main()

Solution (Python):
n, *a = map(int, open(0).read().split())
half_a = sum(a)//2
tmp = 0
for i in range(n):
    if tmp + a[i] >= half_a:
        ans1 = abs(tmp + a[i] - half_a) + abs(sum(a[i+1:]) - half_a)
        ans2 = abs(tmp - half_a) + abs(sum(a[i:]) - half_a)
        ans = min(ans1, ans2)
        break
    tmp += a[i]
print(ans)

Solution (Python):
N = int(input())
la = list(map(int, input().split()))

S = sum(la)
lsum = 0
i = 0
while lsum < S/2:
    lsum += la[i]
    i += 1

sm = min(lsum , lsum-la[i-1])

if lsum - S/2 > S/2 - (lsum-la[i-1]):
    print(S - 2*(lsum-la[i-1]))
else:
    print(2*lsum - S)

Solution (Python):
import sys
from itertools import accumulate

input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))

    cumsum_A = list(accumulate(A))
    sum_A = sum(A)

    ans = float("inf")
    for i in range(N - 1):
        
        cost = abs(sum_A - 2 * cumsum_A[i])
        if cost < ans:
            ans = cost

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
from itertools import accumulate

input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))

    cumsum_A = list(accumulate(A))
    sum_A = sum(A)

    ans = float("inf")
    for i in range(N - 1):
        cost = abs((sum_A - cumsum_A[i]) - cumsum_A[i])
        if cost < ans:
            ans = cost

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys

input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))

    sum_A = sum(A)
    center = sum_A / 2
    total = 0
    near_center = 0
    for a in A:
        total += a
        if abs(total - center) < abs(near_center - center):
            near_center = total

    ans = abs((sum_A - near_center) - near_center)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
*a, = map(int, input().split())
s = sum(a)
ans = s
tmp = 0
for i in a[:-1]:
    tmp += i
    ans = min(ans, abs(tmp*2 - s))
print(ans)

Solution (Python):
n,*a=map(int,open(0).read().split())
l=[a[0]]*n
for i in range(1,n):
  l[i]=l[i-1]+a[i]
r=[l[-1]]*n
for i in range(1,n):
  r[i]=r[i-1]-a[i-1]
ans=10**20
for i in range(n-1):
  ans=min(abs(l[i]-r[i+1]),ans)
print(ans)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
b=(sum(a))/2
count=0
if n==2:
    ans=int(abs((b-a[0])*2))
else:
    for i in range(n):
        count+=a[i]
        if b<=count:
            if i==0:
                c=count
                d=count+a[i+1]
            else:
                c=count-a[i]
                d=count
            break
    e=min(abs(c-b),abs(d-b))
    ans=int(e*2)
print(ans)

Solution (Python):
import itertools
n = int(input())
a = list(map(int, input().split()))

a = list(itertools.accumulate(a))

target = a[-1]
for i in a:
    target = min(abs(a[-1] - i * 2), target)

print(target)

Solution (Python):


import sys
input= lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**9)
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
def lispin(t=int):return list(pin(t))

def resolve():
    N,=pin()
    A=lispin()
    temp=0
    sumA=[0]*N
    sumA[0]=A[0]
    for j in range(1,N):
        sumA[j]=sumA[j-1]+A[j]
    
    ans=2**32-1
    t=sumA[-1]
    for i in range(N):
        ans=min(ans,abs(t-sumA[i]*2))
        
    print(ans)

resolve()

Solution (Python):

import sys

import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement


from operator import itemgetter
from sys import stdin

from operator import mul
from functools import reduce
from collections import Counter





j=0
k=0
n=3
r=1
a=[0]






"1行1つの整数を入力を取得し、整数と取得する"




"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

for i in number_list:
    print(number_list[i-1])

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'''
x=[]
y=[]
for i in range(N):
    x1, y1=[int(i) for i in input().split()]
    x.append(x1)
    y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''

'''
mixlist=[]
for i in range(N):
    a,b=input().split()
    mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ，今回はリスト一つで処理している"
'''

'''



"正方行列にstr型の値を入力"
'''




'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"


'''
table = [[int(i) for i in input().split()] for m in range(m)]

print(type(N))
print(N)
print(type(M))
print(M)

print(type(table))
print(table)
'''











'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''




'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''



'''
A, B, C=stdin.readline().rstrip().split()
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''




"aという変数に入っているものを大文字にして出力"

















'''
コンビネーションの組み合わせの中身を出力する形式
for i in itertools.combinations(brray, 2)
combinationsをpermutationsにすれば順列になる
今回なら(abc133B)
入力
1 2
5 5
-2 8
出力
[[1, 2], [5, 5], [-2, 8]]
もちろん一次元リストでも使えるし
何よりiもリストのように使えるので便利
'''


'''
def cmb(n,r):
    
    r= min(n-r,r)
    
    if r == 0: return 1
    over = reduce(mul, range(n, n-r, -1))
    
    
    

    under = reduce(mul, range(1, r+1))
    
    
    
    

    return over // under
    
    
    
    
a = cmb(n, r)

'''

'''
import itertools
from itertools import combinations_with_replacement

combinationについて
以下の違いを意識しよう
combinations() p, r 長さrのタプル列、ソートされた順で重複なし

combinations_with_replacement() p, r 長さrのタプル列、ソートされた順で重複あり


使用例 　　　　　　　　　　　                  出力　　
combinations('ABCD', 2)　　　　　　　　　　　　AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)　　 AA AB AC AD BB BC BD CC CD DD
'''



'''




for i in a.most_common(n):print(i)





 


'''









'''
bisect.bisect_left(a, x, lo=0, h=len(a))
引数
a: ソート済みリスト
x: 挿入したい値
lo: 探索範囲の下限
hi: 探索範囲の上限
(lo, hiはスライスと同様の指定方法)
bisect_leftはソートされたリストaに対して順序を保ったままxを挿入できる箇所を探索します。leftが示す通り、aにすでにxが存在している場合は、挿入箇所は既存のxよりも左側になります。また、lo, hiを指定することで探索範囲を絞り込むことも可能です。デフォルトはaの全体が探索対象です。
'''

'''
素数の判定
'''


def is_prime(n):
    if n == 1: return False

    for k in range(2, int(np.sqrt(n)) + 1):
        
        if n % k == 0:
            return False
            
    return True


'''
npのmaxとmaximumの違い
xs = np.array([1, -2, 3])
np.max(xs, 0)
この出力は3となります．[1, -2, 3]と0の4つの数字のうち，最も大きい値を出力します．

一方で，[max(1, 0), max(-2, 0), max(3, 0)]を出力したい時があります．
その時は，numpyのmaximum関数を用います．

xs = np.array([1, -2, 3])
np.maximum(xs, 0)  

'''












def main():

    w=1
    j=0
    k=0
    dlen=0
    dsum=0
    ota=0
    n=int(input())
    al=list(map(int, input().split(" ")))
    dlen=sum(al)
    for i in range(n):
        dsum=dsum+al[i]
        if dsum*2 > dlen:
           ota=dsum-al[i]
           break

    
    
    
    
    print(min(abs(2*dsum-dlen),abs(2*ota-dlen)))
    
    
    
    
    
    DP = np.zeros(w+1, dtype=int)
    exdp=np.zeros((3,4)) 
    
    
    
        
        
    
    
        
        
    


    "1行1つの整数を入力を取得し、整数と取得する"
    
    
    "12 21 332 とか入力する時に使う"
    "1行に複数の整数の入力を取得し、整数として扱う"
    
    


    
    
    
    '''
    入力
    1234
    出力
    [1, 2, 3, 4]
    '''
    pin_l=["x" for i in range(10)]
    

    ls = ["a", "b", "c", "d", "e"]


    
    

    
    

    
    
    
    
    
    '''
    lsというリストの場合に、1つ飛びの値を取得したい場合には
    ls[::2]
    のようにします。こうすると、
    ["a", "c", "d"]と出力される
    '''

if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
a_inputs = list(map(int,input().split()))
len_bar = sum(a_inputs)

cum_bar = [0]*n
cum_bar[0]=a_inputs[0]
for i in range(1,n):
    cum_bar[i]=cum_bar[i-1]+a_inputs[i]

gap = float('inf')
for i in range(n-1):
    g = abs(len_bar-2*cum_bar[i])
    if g<gap:
        gap=g
print(gap)

Solution (Python):
N = int(input())
arr = list(map(int, input().split()))
first = 0
second = sum(arr)
min_delta = second - first
for i in range(N):
    first += arr[i]
    second -= arr[i]
    min_delta = min(abs(second - first), min_delta)

print(min_delta)

Solution (Python):
n = int(input())
A = list(map(int, input().split()))

csum = [0] * n
csum[0] = A[0] 
for i in range(1, n):
	csum [i] = csum[i - 1] + A[i]

mind = 1 << 40
sumA = csum[-1]
for i in range(n):
	diff = abs(sumA - 2 * csum[i])
	mind = min(mind, diff)

print(mind)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
l = sum(a)
accu = 0
for i in a:
    accu += i
    if accu>l/2:
        if abs(l/2-accu)<abs(l/2-accu+i):
            print(accu*2-l)
        else:
            print(l-(accu-i)*2)
        break

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

t1 = 0
t2 = sum(a)
ans = 10**18
for i in a:
    t1 += i
    t2 -= i
    ans = min(ans, abs(t1 - t2))
print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
s = sum(a)
x = 0
m = s
for i in range(n):
    x += a[i]
    m = min(m, abs(s-x*2))
print(m)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
s = sum(a)
d = s // 2
t = 0
i = -1
while(t <= d):
    i += 1
    t += a[i]
t2 = t - a[i]


print(min(t - (s - t),(s - t2) - t2))

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
sA = [A[0]]
d = []
for i in range(1, N):
    sA.append(sA[-1] + A[i])

for i in range(N):
    d.append(abs(sA[i] - (sA[-1] - sA[i])))
print(min(d))

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

n = int(input())
a = list( map(int, input().split()))

from itertools import accumulate
acc = [0] + a
acc = list(accumulate(acc))

suma = sum(a)

ans = float('inf')

for i in range(n):
    ans = min(abs( 2*acc[i]-suma  ),ans  )

print(ans)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
s=sum(a)
ans = 12345678901234
cnt = 0
for i in range(n):
    cnt += a[i]
    ans = min(ans,abs(s-cnt - cnt))
print(ans)

Solution (Python):
import sys

def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))

def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]

def to_bin(x: int) -> str: return format(x, 'b') 
def to_oct(x: int) -> str: return format(x, 'o') 
def to_hex(x: int) -> str: return format(x, 'x') 
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]

from itertools import accumulate as acc
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left


def main():
    n = II()
    aa = MII()
    aa_acc = list(acc([0]+aa))
    min_num = 0
    min_d = abs(2*aa_acc[1]-aa_acc[n])
    for i in range(2,n):
        l = aa_acc[i]
        r = aa_acc[n] - aa_acc[i]
        min_d = min(min_d, abs(l-r))
    print(min_d)

if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

length = sum(A)
center = length / 2

now = 0
for i in range(N):
    now += A[i]
    if now == center:
        print(0)
        break
    if now > center:
        print(int(min(now-center, center-now+A[i]) * 2))
        break

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
def Csum(a):
    b,c=[0],0
    for i in range(len(a)):
        c+=a[i]
        b.append(c)
    return b
b=Csum(a)
c=sum(a)
d=[]
for i in range(1,n):
    d.append(abs((c-b[i])-b[i]))
print(min(d))

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
_sum = sum(A)
diff = [0]*(N-1)
cumul = 0
for i in range(N-1):
    cumul += A[i]
    diff[i] = abs(cumul - (_sum - cumul))

print(min(diff))

Solution (Python):
N=int(input())
A=list(map(int,input().split()))

S=[]
s=0
for i in range(N):
    s+=A[i]
    S.append(s)
sm=sum(A)
ans=10**18
for i in range(N):
    val=abs(S[i]-(sm-S[i]))
    ans=min(ans,val)
print(ans)

Solution (Python):
from itertools import accumulate
def myAnswer(N:int,A:list) -> int:
   accum = [A[0]]
   accumRev = [sum(A)]
   ans = 10**10
   for i in range(1,N):
      accumRev.append(accumRev[-1] - A[i-1])
      accum.append(accum[-1]+A[i])
   for i in range(len(accum)-1):
      ans = min(ans,abs(accumRev[i+1] - accum[i]))
   return ans
      
def modelAnswer(N:int,A:list) -> int:
   T1 = [A[0]]
   T2 = [sum(A)]
   for i in range(1,N): 
      T1.append(T1[-1]+A[i])
      T2.append(T2[0] - T1[i-1])
   
   ans = 10**10
   for i in range(len(T1)-1): 
      
      ans = min(ans,abs(T1[i]-T2[i+1]))
   return ans


def main():
   N = int(input())
   A = list(map(int,input().split()))
   
   
   print(myAnswer(N,A[:]))
if __name__ == '__main__':
   main()

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

tmp = [0 for i in range(N+1)]
length = 0
for i in range(N):
  tmp[i+1] = tmp[i] + A[i]
  length += A[i]
  
ans = 10 ** 10
for i in range(1, N+1):
 ans = min(ans, abs((length - tmp[i]) - tmp[i]))

print(ans)