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):

"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq


def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   

def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    


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

    
def main(): 
    S = [0]*N
    S[0] = A[0]
    for n in range(1,N):
        S[n] += S[n-1]+A[n]
    S2 = S[n]/2
    li = bisect.bisect_left(S, S2)

    if S2 == S[li]:
        return print(0)
    if abs(S2 - S[li-1]) < abs(S[li]-S2):
        rod1 = S[li-1]
    else:
        rod1 = S[li]
    rod2 = S[n]-rod1
    res = abs(rod1-rod2)

        
    print(int(res))
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()



"""
N, X = map(int, input().split())

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

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())


all(nstr.count(c) for c in '753')


ABT = zip(A, B, totAB)

A, B, totAB = zip(*ABT)


(x >> i) & 1


dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break

add = 1 
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)


li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    


org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)




    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""

Solution (Python):




from __future__ import print_function, division, unicode_literals

__metaclass__ = type

try:
    input = raw_input
    range = xrange
except NameError:
    pass


import sys












def main():
    N = int(input())
    A = [int(x) for x in input().split()]
    tot = sum(A)
    i = 0
    psum = 0
    while i < N and 2*psum < tot:
        psum += A[i]
        i += 1
    print(min(2*psum - tot, tot - 2*(psum - A[i - 1])))


if __name__ == "__main__":
    main()

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





sum = 0
for i in range(N):
  sum += A[i]


half1st = 0
half1st2 = 0
half2nd = 0
i = 0
temp = 0
flag = 0
for i in range(N):
  if( half1st <= (int)(sum/2) ):
    half1st += A[i]
    temp += 1
  else:
    half2nd += A[i]
thre = temp-1
half1st2 = half1st - A[thre]
half2nd1 = half2nd + A[thre]

P = abs(half1st2 - half1st)
Q = abs(half1st - half2nd)
R = abs(half1st2 - half2nd1)

if (half1st2 == half2nd1):
  print(0)

elif ( P < Q and P < R):
  
  print(P)
elif (Q < R):
  
  print(Q)
else:
  print(R)

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

def h(n,A):
    res = float('inf')
    f = []
    b = []
    t = 0
    for i in range(len(A)):
        t+=A[i]
        f.append(t)
    t = 0
    for i in range(len(A)-1,-1,-1):
        t += A[i]
        b.append(t)
    b.reverse()
    for i in range(len(A)-1):
        temp1 = f[i]
        temp2 = b[i+1]
        res = min(res,abs(temp1-temp2))
        
    
    
    print(res)
    
    
    
h(n,A)

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split()))
    start_len = sum(A)
    mokuteki = start_len/2
    temp = 0
    for n in range(N):
        temp += A[n]
        if(temp >= mokuteki):
            break
    n1 = n-1
    kouho1 = temp - A[n]
    n2 = n
    kouho2 = temp
    kouho1_ = start_len - kouho1*2
    kouho2_ = kouho2*2 - start_len
    res = min(kouho1_, kouho2_)
    print(res)
            

if __name__ == "__main__":
    main()

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

def func(A):
    A_inf = 0
    A_sup = 0
    N_inf = 0
    N_sup = 0
    L = sum(A)

    for a in A:
        if A_inf <= L/2 - a:
            A_inf += a
            A_sup += a
            N_inf += 1
            N_sup += 1
            continue
        else:
            if A_sup <= L/2 and A_sup + a > L/2:
                A_sup += a
                N_sup += 1
            break

    if A_inf == A_sup:
        return 0

    A_mid = A_sup - A_inf
    A_left = L/2 - A_inf
    A_right = A_sup - L/2
    A_lrmin = min(A_left, A_right)
    if A_mid-1 >= 2*A_lrmin:
        return int(2*A_lrmin)
    else:
        return int(A_mid)

print(func(A))

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

sep = N//2
for i in range(N):
  if sum(A[:sep]) >= sum(A[sep:]):
    sep -= N//((i+2)**2)
  else:
    sep += N//((i+2)**2)
  if N//((i+2)**2) == 1:
    break



a = abs(sum(A[:sep])-sum(A[sep:]))
b = abs(sum(A[:sep+1])-sum(A[sep+1:]))
c = abs(sum(A[:sep-1])-sum(A[sep-1:]))
d = abs(sum(A[:sep+2])-sum(A[sep+2:]))
e = abs(sum(A[:sep-2])-sum(A[sep-2:]))
print(min(a,b,c,d,e))

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

for a in A:
    sum += a
check = sum / 2

for b in A:
    sum1 += b
    if check < sum1:
        sum2 = sum1 - b
        break
sum1_2 = sum - sum2
sum2_2 = sum - sum1
if (sum1_2 - sum2) > (sum1 - sum2_2):
    print(sum1 - sum2_2)
else:
    print(sum1_2 - sum2)

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


def main():
    N = int(input())
    A = list(map(int, input().split()))
    s = sum(A)
    a = 0
    b = 0
    tmp = []
    for i in range(len(A)):
        if s % 2 != 0:
            if a >= (s // 2) - 1 or i == N-1:
                b += A[i]
            else:
                a += A[i]
                tmp.append(A[i])
        else:
            if a >= (s // 2) or i == N-1:
                b += A[i]
            else:
                a += A[i]
                tmp.append(A[i])
    ans1 = abs(a-b)
    ans2 = abs((a-tmp[-1]) - (b+tmp[-1]))
    print(min(ans1, ans2))


if __name__ == '__main__':
    main()

Solution (Python):
n=int(input())
a=input().split()
a=[int(i) for i in a]
l=0
r=0
s=sum(a)/2
for i in range(n):
	l=a[i]+l
	if l>=s and abs(l-s)>=abs(l-s-a[i]):
		print(int(abs(l-s-a[i])*2))
		exit()
	elif l>=s and abs(l-s)<=abs(l-s-a[i]):
		print(int(abs(s-l)*2))
		exit()

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

def getNearestValue(list, num):
  idx = np.abs(np.asarray(list) - num).argmin()
  return list[idx]

a=(np.cumsum(A))
l=getNearestValue(a, sum(A)/2)

ans=abs(sum(A)-2*l)
print(ans)

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

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


































left = A[0]
right = A[-1]

front = 1
back = 1
for _ in range(N-2):
    if left > right:
        right += A[-1 - back]
        back += 1
    else:
        left += A[front]
        front += 1

print(abs(left-right))

Solution (Python):
import sys
from collections import deque

input = sys.stdin.readline
n = int(input())
a = deque()
a = deque(map(int, input().split()))
asum = sum(a)
ah = asum / 2
it = a.popleft()
l1 = [it]
sl1 = it
sl2 = asum
dp = []
sdp = 0

for i in range(n - 1):
    it = a.popleft()
    dp = l1
    sdp = sl1
    l1.append(it)
    sl1 += it
    sl2 -= it
    if sl1 > ah:
        break
if (sl1 - ah) ** 2 + (asum - sl1 - ah) ** 2 > (sdp - ah) ** 2 + (asum - sdp - ah) ** 2:
    l1 = dp
    a.append(it)
    sl1 = sdp
    sl2 += it
print(int(abs(sl1 - ah) * 2))

Solution (Python):
n = int(input())
a = list(int(x) for x in input().split(" "))
center = sum(a) / 2

sum = 0
diff = float('inf')
for x in a:
    if abs(sum + x - center) > diff:
        break
    sum += x
    diff = abs(sum - center)

print(int(diff * 2))

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30

def main():
    n = int(input().strip())
    v = list(map(int, input().strip().split()))

    a = [0] * n
    b = [0] * n
    for i in range(n):
        if i == 0:
            a[i] = v[i]
            continue
        a[i] = a[i-1] + v[i]
    for i in reversed(range(n)):
        if i == n-1:
            b[i] = v[i]
            continue
        b[i] = b[i+1] + v[i]
    ans = INF
    for i in range(n-1):
        ans = min(ans, abs(a[i] - b[i+1]))
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):

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

left = A[0]
left_count = 0
right = A[N - 1]
right_count = 0
for i in range(N - 2):
    if left <= right:
        left_count += 1
        left += A[left_count]
    else:
        right_count += 1
        right += A[N - right_count - 1]

print(abs(left- right))

Solution (Python):
N = int(input())
A = [int(i) for i in input().split()]
A_sum = sum(A)

s = 0
i = 0
while i < N:
    s += A[i]
    if A_sum - s < s:
        t = s
        u = s - A[i]
        break
    i += 1
      
print(min(t-A_sum+t, A_sum-u-u))

Solution (Python):
n=int(input())
li=list(map(int,input().split()))
a=0
for i in range(0,n):
  a=a+li[i]
total=0
k=0
while 2*total<=a:
  total=total+li[k]
  k=k+1
if 2*total==a:
  print(0)
else:
  if 2*total-a<=a-2*(total-li[k-1]):
    print(2*total-a)
  elif 2*total-a>a-2*(total-li[k-1]):
    print(a-2*(total-li[k-1]))

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


diff = 2020202020 * 200000 + 1
tot = sum(A)

temp1 = 0

for i in range(N):
    temp1 += A[i]
    
    temp3 = abs(tot - 2 * temp1)
    if temp3 <= diff:
        
        diff = temp3
    else:
        break

print(diff)

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

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

sum_of_an = sum(An)

if sum_of_an % 2 == 0:
    half_of_an = sum_of_an / 2
    sum_left_len = 0
    for l in An:
        sum_left_len += l
        if sum_left_len == half_of_an:
            print(0)
            exit(0)
        elif sum_left_len > half_of_an:
            break
min_yen = None
left_len = 0
for (i, l) in zip(range(0, N), An):
    if i == N - 1:
        break

    left_len += l
    if min_yen is None:
        min_yen = abs(sum_of_an - left_len * 2)
    else:
        min_yen = min(min_yen, abs(sum_of_an - left_len * 2))

print(min_yen)

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
S = sum(A)
b = 0
a = 0
c = 0
if N == 2:
    print(abs(A[0]-A[1]))
else:
    for i in range(len(A)):
        if S/2-0.5 > a:
            a += A[i]
        else:
            b = a + A[i]
            c = a - A[i-1]
            break
        if i == len(A)-1:
            b = a
            a = a-A[i]
        else:
            None
    print(min(abs(S - a*2), abs(S - b*2),abs(S-c*2)))

Solution (Python):

N = int(input())
A_list = list(map(int, input().split()))
 
div_sum_A = sum(A_list) / 2
ans = 0
calculator = 0
for i in range(N):
    calculator += A_list[i]
    if calculator >= div_sum_A:
        if calculator == div_sum_A:
            ans = 0
            break
        elif A_list[i] > div_sum_A:
            ans = 2 * A_list[i] - calculator
            break
        else:
            cand_1 = calculator - (2 * div_sum_A - calculator)
            cand_2 = abs((calculator - A_list[i]) - (2 * div_sum_A - (calculator - A_list[i])))
            ans = min(cand_1, cand_2)
            break

print(int(ans))

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
m = sum(A) // 2
n = 0
if N > 2:
  for i in range(N):
    if n < m:
      n += A[i]
    elif n >= m and i == N - 1:
      a = i
    elif n >= m and i != N - 1:
      a = i
      break
  if a == 0:
    print(abs(A[a]-sum(A[a:])))
  elif abs(sum(A[:a-1]) - sum(A[a-1:])) > abs(sum(A[:a]) - sum(A[a:])):
    print(abs(sum(A[:a]) - sum(A[a:])))
  else:
    print(abs(sum(A[: a - 1]) - sum(A[a - 1 :])))
else:
  print(abs(A[0]-A[1]))

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

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
a = inpl()
s = sum(a)
cnt = 0
res = INF
b = [0] * n
for i in range(n-1):
    a[i+1] = a[i+1] + a[i]
for i in range(n):
    res = min(res,abs(s-a[i]-a[i]))
print(res)

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

A_sum = sum(A)
A_sum_hulf = A_sum / 2

A_sum_rui = 0

for i in range(N):
    A_sum_rui += A[i]
    if A_sum_rui > A_sum / 2:
        if A_sum_rui - (A_sum / 2) < (A_sum / 2) -(A_sum_rui - A[i]):
            print(A_sum_rui - (sum(A) - A_sum_rui))
        else:
            print(sum(A) - 2 * (A_sum_rui - A[i]))
        break

Solution (Python):
import numpy as np
N=int(input())
A=list(map(int, input().split()))
A=np.array(A)
left=0 
right=N-1
while left<right:
  mid=(left+right)//2
  if A[:mid+1].sum()<A[mid+1:].sum():
    left=mid+1
  else:
    right=mid
if (abs(A[:left+1].sum()-A[left+1:].sum()))>(abs(A[:left].sum()-A[left:].sum())):
  print((abs(A[:left].sum()-A[left:].sum())))
else:
  print((abs(A[:left+1].sum()-A[left+1:].sum())))

Solution (Python):
import math
N = int(input())
li = list(map(int,input().split()))

leng=sum(li)

leng2=0
count=0

for i in range(N):
  if leng2<leng/2:
    leng2+=li[i]  
  
  if leng2==leng/2 and leng%2 ==0:  
    print(count)
    break
    
  elif leng2>leng/2:
    if i>0:
      xx = abs(leng/2 - leng2)
      xxx = abs(leng/2 - leng2 + li[i])
      if xx < xxx:
        count = xx/0.5
      else:
        count = xxx/0.5
    elif i==0:
      xx = abs(leng/2 - leng2)
      count = xxx/0.5
    print(int(count))
    break

Solution (Python):
import math

n = int(input())
a = [int(i) for i in input().split(" ")]

sum_length = sum(a)
min_diff = 1e18
r = 0

for i in range(len(a)):
    r += a[i]
    l = sum_length - r
    if(abs(r - l) <= min_diff):
        min_diff = abs(r - l)
        
print(min_diff)

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

    sm = sum(A)
    agg = 0
    idx = 0
    mid = sm / 2
    shrink_cnt = sm - N
    while agg < mid and idx < N-1:
        
        agg += A[idx]
        idx += 1
    
    oneleft = agg
    oneright = sm - oneleft 
    twoleft = agg-A[idx-1]
    tworight = sm - twoleft
    ans = min(abs(oneleft-oneright), abs(twoleft-tworight))

    print(int(ans))

if __name__ == '__main__':
    solve()

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

s=sum(A)
left=0
right=n-1

while(left+1<right):
    if 2*sum(A[0:(left+right)//2])>s:
        right=(left+right)//2
    elif 2*sum(A[0:(left+right)//2])<s:
        left = (left+right)//2
    else:
        left=(left+right)//2
        right=(left+right)//2
        break

print(min(abs(s-2*sum(A[0:left+1])),abs(s-2*sum(A[0:left]))))

Solution (Python):
from bisect import bisect_left, bisect, insort_left, insort
from itertools import accumulate
INF = float("inf")
def solve():
    n = int(input())
    A = list(map(int, input().split()))
    sum_a = sum(A)
    X = list(accumulate(A))
    Y = list(accumulate(A[::-1]))
    Z = {sum_a // 2, (sum_a + 1) // 2}
    def f(z, B):
        ret = INF
        left = bisect_left(B, z)
        for a in [left, left + 1]:
            if a == n + 1:
                continue
            if a < n - 1:
                t = B[a]
                ret = min(ret, abs(t - (sum_a - t)))
            if a <= n:
                t = B[a - 1]
                ret = min(ret, abs(t - (sum_a - t)))
        return max(0, ret)
    ans = INF
    for z in Z:
        ans = min(ans, f(z, X), f(z, Y))
    print(ans)
solve()

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

Solution (Python):
from itertools import accumulate
import sys
n=int(input())
A=list(map(int,input().split()))
S=sum(A)/2
B=list(accumulate(A))

for i in range(n):
    B[i]-=S
    if B[i]<0:
        continue
    elif B[i]==0:
        print(0)
        sys.exit()
    else:
        if i==0:
            print(A[0]-A[1:])
        elif i>0 and i<n-1:
            a=abs(sum(A[:i])-sum(A[i:]))
            b=abs(sum(A[:i+1])-sum(A[i+1:]))
            print(min(a,b))
        else:
            print(A[n-1]-sum(A[:n-1]))
        sys.exit()

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
p=sum(A)//2
S=0
cost=0
i=0
while S<p:
  S=S+A[i]
  i=i+1

if S==p:
  cost=0
else:
  if sum(A[0:i])>sum(A[i-1:N]):
    cost=sum(A[i-1:N])-sum(A[0:i-1])
  else:
    cost=sum(A[0:i])-sum(A[i:N])
print(cost)

Solution (Python):
from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math

N = int(stdin.readline().rstrip())
d = [int(s) for s in stdin.readline().rstrip().split()]
count = 0
sumF = d[0]
sumB = d[len(d) - 1]
count = 0
countF = 0
countB = len(d) - 1
while count < len(d):
    if sumF < sumB:
        sumF += d[countF+1]
        countF += 1
        count += 1
    elif sumB < sumF:
        sumB += d[countB-1]
        countB -= 1
        count += 1
    else:
        sumF += d[countF+1]
        countF += 1
        sumB += d[countB-1]
        countB -= 1
        count += 2
print(abs(sum(d[0:countF])-sum(d[countF:len(d)])))

Solution (Python):
N=int(input())
A = list(map(int,input().split()))
A2 = [ A[i]*2 for i in range(N) ]
asum = sum(A2)
tgt = asum//2
tmpa = 0
ans = 0
for i in range(N):
  tmpa += A2[i]
  if tmpa >= tgt:
    if i == 0:
      ans = tmpa - tgt
    else:
      ans = min(tmpa-tgt, tgt-(tmpa-A2[i]))

    break
print(ans)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
sumFrontHalf=0
halfIndex=0
sumA=sum(a)
for i in range(n):
  sumFrontHalf+=a[i]
  if sumFrontHalf>=sumA/2:
    halfIndex=i
    break
sumBackHalf=sumA-sumFrontHalf+a[halfIndex]
if sumFrontHalf<sumBackHalf:
  print(sumFrontHalf-sumBackHalf+a[halfIndex])
else:
  print(sumBackHalf-sumFrontHalf+a[halfIndex])

Solution (Python):

from math import ceil
N = int(input())
A = list(map(int, input().split()))
total = sum(A)
half = ceil(sum(A) / 2)
tmp = 0
diff = sum(A)
for i in range(N):
    tmp += A[i]
    total -= A[i]
    if total == tmp:
        print(0)
        exit()
    diff = min(diff, abs(total - tmp))
print(diff)

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

left_length = sum(A[:int(N/2)])
right_length = sum(A[int(N/2):])
if left_length > right_length :
  price = left_length - right_length
  for i in range(int(N/2)-1,0,-1) :
    var = abs(sum(A[:i]) - sum(A[i:]))
    if price > var :
      price = var
    else :
      break
else :
  price = right_length - left_length
  for i in range(int(N/2)+1,N) :
    var = abs(sum(A[i:]) - sum(A[:i]))
    if price > var :
      price = var
    else :
      break

print(price)

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

all_length = sum(A)
sum_length = 0
num = 0

for i in range(N):
    sum_length += A[i]
    if sum_length >= all_length // 2:
        num = i + 1
        break

half_l1 = [A[i] for i in range(num-1)]
sum_half_l1 = sum(half_l1)
rest1 = all_length - sum_half_l1

half_l2 = [A[i] for i in range(num)]
sum_half_l2 = sum(half_l2)
rest2 = all_length - sum_half_l2

need = min(abs(sum_half_l1 - rest1), abs(sum_half_l2 - rest2))
print(need)

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

len=sum(a)
len_l=0
for i in range(n):
    if len/2>len_l:
        len_l+=a[i]
    else:
        center=i-1
        break
else:
    center=n-1
    
len_r=len-len_l
len_l-=a[center]

d=len/2-max(len_r,len_l)

print(int(d*2))

Solution (Python):

import sys
f = sys.stdin
n = int(f.readline())
a = list(map(int, f.readline().split(' ')))

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

def sum_fragment(p, q, prefix):
    return prefix[q+1] - prefix[p]

l = prefix[n]
diff = l
k = 0
for i in range(1, n):
    l1 = prefix[i]
    if l == 2*l1:
        k = i
        diff = 0
        break
    if l < 2*l1:
        if diff > (2*l1 - l):
            k = i
            diff = 2*l1 - l
        break
    diff = l - 2*l1
    k = i

print(diff)

Solution (Python):


import itertools
import sys


class CumulativeSum(object):

    def __init__(self, sequence):
        self.cumulative_sum = [0]
        self.cumulative_sum.extend(itertools.accumulate(sequence))

    def partial_sum(self, first, last):
        return self.cumulative_sum[last + 1] - self.cumulative_sum[first]


def div_ceil(a, b):
    return (a + b - 1) // b


def solve(n, xs):
    cs = CumulativeSum(xs)
    res = sys.maxsize // 10
    for p in range(n):
        left_sum = cs.partial_sum(0, p - 1)
        right_sum = cs.partial_sum(p, n - 1)
        res = min(res, abs(right_sum - left_sum))
    return res


def main():
    n = int(input())
    xs = [int(x) for x in input().split()]
    res = solve(n, xs)
    print(res)


if __name__ == "__main__":
    main()

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

s = sum(A)

oe = s % 2
h = s // 2

p = 0
p0 = None
p1 = None
for i in A:
    p += i
    if p == h:
        if oe == 0:
            print(0)
            exit()
        print(1)
        exit()
    if p > h:
        p1 = p
        break
    p0 = p

if oe == 1:
    h += 1

p = p0 if p1 == s or abs(p0 - h) < abs(p1 - h) else p1

print(abs(p*2 - s))

Solution (Python):
import sys
input = sys.stdin.readline
import numpy as np
 
N=int(input())
A = np.array([int(x) for x in input().split()])
if N==2:
  print(abs(A[0]-A[1]))
else:
  B = np.concatenate([[0],A.cumsum()])
  H = np.searchsorted(B,sum(A)//2)
  result=float('inf')
  for i in range(min(5,len(A)//2)):
    result=min(result,abs(sum(A[:H+i])-sum(A[H+i:])),abs(sum(A[:H-i])-sum(A[H-i:])))

  print(result)

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

dp = [sum(A)]
for i in range(N):
  dp.append(dp[i]-2*A[i])
import numpy as np
print(min(np.abs(dp)))

Solution (Python):
N = int(input())
list = [int(i) for i in input().split()]

forward = 0
backward = N-1

sum = list[forward]
sum2 = list[backward]
while (True):
    if backward - forward == 1:
        break
    if sum < sum2:
        forward += 1
        sum += list[forward]
    else:
        backward -= 1
        sum2 += list[backward]
print(abs(sum - sum2))

Solution (Python):
N = int(input())
List = list(map(int,input().split()))
length = sum(List)
sum = 0
center = length / 2
centerIdx = 0
for idx in range(len(List)):
    sum += List[idx]
    if center <= sum:
        centerIdx = idx
        break

if center == sum:
    print(0)
else:
    if (centerIdx == 0):
        print(sum * 2 - length)
    elif (sum -center) < (center - (sum - List[centerIdx])):
        print(sum * 2 - length)        
    else:       
        print(length - (sum - List[centerIdx]) * 2)

Solution (Python):
import numpy as np
import math
n = int(input())
li = list(map(int,input().split()))
half = sum(li) / 2

res = np.cumsum(li)
idx = np.abs(res - half).argmin()
if res[idx] == half:
    ans = 0
else:
    ans = abs(res[idx] - (res[-1] - res[idx]))
print(int(ans))

Solution (Python):
def main():
    N=int(input())
    A=list(map(int,input().split()))
    total=sum(A)
    tmp=0
    for a in A:
        tmp+=a
        if 2*tmp>=total:
            break
    re_A=reversed(A)
    re_tmp=0
    for re_a in re_A:
        re_tmp+=re_a
        if 2*re_tmp>=total:
            break
    if tmp>re_tmp:
        print(2*re_tmp-total)
    else:
        print(2*tmp-total)
        
    
if __name__=='__main__':
    main()

Solution (Python):
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
n = int(input())
a = list(map(int,input().split()))
pre = [0 for i in range(n)]
pre[0] = a[0]
for i in range(1,n):
	pre[i] = pre[i-1] + a[i]
minn = abs(pre[-1]-2*pre[0])
for i in range(1,n):
	minn = min(minn,abs(pre[-1]-2*pre[i]))
print(minn)

Solution (Python):

MOD = 10 ** 9 + 7

import math



def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def main():

    n=int(input())
    a=list(map(int,input().split()))
    s=0
    suma=sum(a)
    temp=0
    for i in range(len(a)):
        temp+=a[i]
        if temp>= suma//2:
            p=i
            break
        p=i
    x=temp
    y=suma- temp

    if abs(x-y)>abs(temp-a[p]-abs(suma-temp+a[p])):
        x=temp-a[p]
        y=suma-temp+a[p]


    s=min(abs(suma//2-x),abs(suma//2-y))
    s*=2
    if suma%2!=0:
        s+=1
    print(s)

if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
forward = [0]*N
forward[0] = A[0]
total = sum(A)
m = 10**12
for i in range(1, N):
    forward[i] = forward[i-1] + A[i]
for i in range(N-1):
    tmp = total - forward[i]
    diff = abs(tmp - forward[i])
    m = min(diff, m)

print(m)

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

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

count = 0
cost = 0
temp = 0
temp2 = 0
ans1 = 0
ans2 = 0
nokori = 0
sum = sum(a)
half = int(sum/2)
if(sum%2 == 1):
  cost = 1

for i in (a):
  count += i
  if(count == half):
    print(cost)
    sys.exit()
  elif(count > half):
    temp = count
    nokori = sum - temp
    ans1 = temp - nokori
    
    break
    


a.reverse()
count = 0

for j in (a):
  count += j
  if(count > half):
    temp2 = count
    nokori = sum - temp2
    ans2 = temp2 - nokori
    if(ans1 > ans2):
      print(ans2)
    else:
      print(ans1)
    break

Solution (Python):
N = int(input())
a=list(map(int,input().split()))
ans=2020202020
s=sum(a)
mae=a[0]
for i in range(1,N):
    mae+=a[i]
    ato=s-mae
    if mae-ato>0:
        ans=min(abs(sum(a[:i])-sum(a[i:])),abs(sum(a[:i+1])-sum(a[i+1:])))
        break
    else:
        ans=min(ans,abs(mae-ato))
print(ans)

Solution (Python):
import math
cnt = int(input())
data  = list(map(int, input().strip().split()))

avr = int(math.floor(sum(data)/2))
i = 0
sum_ = 0
while sum_ < avr:
    sum_ += data[i]
    i += 1
i = i - 1

left = sum(data[i+1:])
right = sum(data[i+1:])



'''
print("---")
print(i)
print(left)
print(right)
'''
diff = sum(data[:i+1]) - sum(data[i+1:])
diff = abs(diff)
diff2 = sum(data[:i]) - sum(data[i:])
diff2 = abs(diff2)


if diff < diff2:
    print(diff)
else:
    print(diff2)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
ans = 0
s = sum(a)
al = []

sum1 = 0

for i in range(0,n):
        
        
        
        
        sum1 += a[i]
        sum2 = s - sum1
        
        
        al.append(abs(sum1 - sum2))
        if sum1 == sum2:
                print(0)
                exit()

minDiffIdx = al.index(min(al))





tmp1 = sum(a[0:minDiffIdx])
tmp2 = sum(a[minDiffIdx:])


diff1 = abs(tmp1 - tmp2)

tmp3 = sum(a[0:minDiffIdx + 1])
tmp4 = sum(a[minDiffIdx + 1:])


diff2 = abs(tmp3 - tmp4)
print(min(diff1, diff2))