Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.

The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1.

Print an integer — the maximal number of 1s that can be obtained after exactly one move.

NoteIn the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.

x = int(input())
li = list(map(int, input().split()))
ans, cnt = 0,0
for j in range(x):
	cnt = 0
	for i in  range(j,x):
		if li[i]==0:
			cnt += 1
		ans = max(ans,li[: j].count(1)+ cnt + li[i+1:].count(1) )

print(ans if li.count(0) else x-1)

n, a = int(input()), [int(x) for x in input().split()]
if not 0 in a: print(n-1); quit()
s, m = 0, 0
for row in a:
    row = 1 if row == 0 else -1
    s = max(s+row, row)
    m = max(m, s)
print(m+sum(a))

n=int(input())
x=list(input().split())
m=[]
for i in range(n):
    for j in range(i,n):
        m.append(x[:i].count('1')+x[i:j+1].count('0')+x[j+1:].count('1'))
print(max(m))

# import math
# import bisect
import sys
# from collections import OrderedDict
input = sys.stdin.readline
def inp():
	return(int(input()))
def inlt():
	return(list(map(int,input().split())))
def insr():
	s = input()
	return(s[:len(s)-1])
def invr():
	return(map(int,input().split()))
# list1, list2 = zip(*sorted(zip(list1, list2)))
n = inp()
A = inlt()
pre = []
prev = 0
for i in range(n):
	if A[i] == 1:
		prev -= 1
	else:
		prev += 1
	pre.append(prev)
best_j = 0
best_k = 0
maxx = -2
for j in range(n):
	for k in range(j,n,1):
		if j == 0:
			if pre[k] >maxx:
				best_k = k
				best_j = j
				maxx = pre[k]
		else:
			if pre[k]-pre[j-1] > maxx:
				best_k = k
				best_j = j
				maxx = pre[k] - pre[j-1]
out = sum(A)
# print(best_j,best_k)
c = sum(A[best_j:best_k+1])
# print(c)
out += (best_k-best_j+1-c-c)
print(out)

n = int(raw_input())
nums = map(int, raw_input().split(' '))
normal = reduce(lambda a, b: a + b, nums, 0)
costs = map(lambda a: -1 if a == 1 else 1, nums)

result = costs[0]
current = costs[0]

for i in range(1, n):
    if costs[i] > current + costs[i]:
        current = costs[i]
    else:
        current += costs[i]
    if current > result:
        result = current
print result + normal

_ = input()
numbers = [int(n) for n in input().split()]

def get_zero_data(numbers):
    zero_data = []
    i = 0
    while i < len(numbers):
        if numbers[i] == 0:
            data = [i, 1, 0]
            i += 1
            while i < len(numbers) and numbers[i] == 0:
                data[1] += 1
                i += 1
            zero_data.append(data)
        i += 1
    return zero_data

def get_best_solution(numbers, zero_data):
    if not zero_data:
        return len(numbers) - 1
    best_solution, solution = zero_data[0][:], zero_data[0][:]
    for z_data in zero_data[1:]:
        cur_ones_between = z_data[0] - solution[0] - solution[1] - solution[-1]
        if solution[-1] + cur_ones_between < solution[1]:
            best_solution = max(best_solution, solution, key=lambda s: s[1] - s[-1])[:]
            solution[1] += z_data[1]
            solution[-1] += cur_ones_between
        else:
            solution = z_data
    best_solution = max(best_solution, solution, key=lambda s: s[1] - s[-1])
    return sum(numbers) + best_solution[1] - best_solution[2]

zero_data = get_zero_data(numbers)
print(get_best_solution(numbers, zero_data))

import sys
from math import sqrt
input = sys.stdin.readline

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

n = int(input())
bits = list(map(int,input().split()))
res=-1
for i in range(n):
    for j in range(i,n):
        temp = bits.copy()
        for k in range(i,j+1):
            temp[k] = 1-temp[k]
        res = max(temp.count(1),res)
print(res)

#!/usr/bin/env python3

def main():
    from sys import stdin

    n = int(stdin.readline())
    ans = -1
    ones, onesInterval, subarrsum = 0, 0, 0

    for ai in map(int, stdin.readline().split()):

        subarrsum += -1 if ai else 1
        ones += ai

        if subarrsum > ans:
            ans = subarrsum
            onesInterval += ai

        if subarrsum < 0:
            subarrsum = 0
            onesInterval = 0

    print(ans + ones - onesInterval)

if __name__ == "__main__":
    main()

z,zz=input,lambda:list(map(int,z().split()))
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
    p=ceil(x**.5)+1
    for i in range(2,p):
        if (x%i==0 and x!=2) or x==0:return 0

    return 1
def dfs(u,visit,graph):
    visit[u]=True
    for i in graph[u]:
        if not visit[i]:
            dfs(i,visit,graph)

###########################---Test-Case---#################################
"""

"""
###########################---START-CODING---##############################

n=int(z())
l=zzz()

ans=0

for i in range(n):

    for j in range(i+1):
        p=l[:]

        for k in range(j,i+1):
            p[k]=1-p[k]

        ans=max(ans,p.count(1))
print(ans)

n=int(input())
list1=input()
sum1=list1.count('1')
list1=list1.split()
ans=0
for a in range(1,n+1):
    for i in range(n):
      list2=list1[i:a+i]
      suma=sum1-int(list2.count('1'))+int(list2.count('0'))
      ans=max(sum1,suma,ans)
if sum1==n:
    print(ans-1)
else:
    print(ans)

#!/usr/bin
n=int(raw_input())
o=z=_m=m=z_=0
for r in raw_input().split():
    if r=='1':
        o,z=-~o,0
        if z_:m=-~m
    else:
        z_,z=-~z_,-~z
        _m = max(_m, z_-m,z)
        if z_-m <= 0:z_,m=z,0
print [~-n, o+_m][o<n]

a=int(input())
z=list(map(int,input().split()))
t=[z[i] for i in range(len(z))]
for i in range(len(z)):
    if(z[i]==1):
        z[i]=-1
    else:
        z[i]=1

cur=z[0]
ma=z[0]
for i in range(1,len(z)):
    cur=max(z[i],z[i]+cur)
    ma=max(cur,ma)
print(ma+t.count(1))

n = int(input())
l =[int(i) for i in input().split()]
ini_zeros = 0
ini_ones = 0
refer =[]
result = []
a = 0
c = 0
b =0
reverse = []
if sum(l) ==len(l):
    print(len(l)-1)
else:
    for i in range(len(l)):
        if l[i] == 0:
            ini_zeros+=1
            if i != 0 and l[i-1]==1:
                refer.append([ini_ones])
                ini_ones = 0
            if i == len(l)-1:
                refer.append([0,ini_zeros])
        else:
            ini_ones+=1
            if i != 0 and l[i-1] ==0:
                refer.append([0,ini_zeros])
                ini_zeros =0
                if i == len(l) - 1:
                    refer.append([ini_ones])
    if refer[0][0] !=0:     #1打头
        for i in range(len(refer)):
            a += ((-1)**(i-1))*refer[i][-1]
            if a <0:
                a =0
            result.append(a)
    else:
        for i in range(len(refer)):
            a +=((-1)**i)*refer[i][-1]
            if a <0:
                a =0
            result.append(a)
    result.sort()
    b+=sum(l)+result[-1]
    print(b)

_ = input()
numbers = [int(n) for n in input().split()]

def get_zero_data(numbers):
    zero_data = []
    i = 0
    while i < len(numbers):
        if numbers[i] == 0:
            data = [i, 1, 0]
            i += 1
            while i < len(numbers) and numbers[i] == 0:
                data[1] += 1
                i += 1
            zero_data.append(data)
        i += 1
    return zero_data

def get_best_solution(numbers, zero_data):
    if not zero_data:
        return len(numbers) - 1
    best_solution, solution = [*zero_data[0]], [*zero_data[0]]
    for z_data in zero_data[1:]:
        cur_ones_between = z_data[0] - solution[0] - solution[1] - solution[-1]
        if solution[-1] + cur_ones_between < solution[1]:
            best_solution = max(best_solution, solution, key=lambda s: s[1] - s[-1])[:]
            solution[1] += z_data[1]
            solution[-1] += cur_ones_between
        else:
            #best_solution = max(best_solution, solution, key=lambda s: s[1] - s[-1])
            solution = [*z_data]
    best_solution = max(best_solution, solution, key=lambda s: s[1] - s[-1])
    return sum(numbers) + best_solution[1] - best_solution[2]

zero_data = get_zero_data(numbers)
print(get_best_solution(numbers, zero_data))

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 16:47:18 2018

@author: jinbin
"""

n=int(input());s=[int(i) for i in input().split()]+[1];a=m=sum(s)-1
if 0 in s:
    for i in range(s.index(0),n+1):
        if s[i]:
            if not(s[i-1]):
                m=max(a,m)
            a-=1
        else:
            if s[i-1] and a<sum(s)-1:
                a=sum(s)-1
            a+=1
    print(m)
else:
    print(m-1)

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

ll=[]
l1=[]
we=0
cnt=0
for i in range(n):
  if l[i]==1:
    cnt-=1
  else:
    cnt+=1

  ll.append(cnt)
  if cnt<0:
    cnt=0

  if l[i]==1:
    we+=1

print(max(ll)+we)

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

max = 0

for i in range(1, n + 1):
    for j in range(i, n + 1):
        ones = p[n] + j - (i - 1) - (p[j] - p[i - 1]) * 2
        if ones > max:
            max = ones

# print(a)
# print(p)
print(max)

n = int(input())
mas = [int(x) for x in input().split()]

def func(massive, x1, x2):

    for i in range(x1, x2+1):
        massive[i] = 1 - massive[i]

    x = massive.count(1)

    for i in range(x1, x2+1):
        massive[i] = 1 - massive[i]

    return x

mas1 = []
for z1 in range(n):
    for z2 in range(z1,n):
        mas1.append(func(mas, z1, z2))

print(max(mas1))

n = int(input())
a = input().split()

maxSoFar = 0

for i in range(n):
    for j in range(i+1):
        maxSoFar = max(maxSoFar,(a[:j]+a[i+1:]).count('1')+a[j:i+1].count('0'))

print(maxSoFar)

n = int(input())
a = list(map(int, raw_input().split()))
x = 0
for i in range(n):
    for j in range(i, n):
        y = 0
        for k in range(n):
            if k >= i and k <= j:
                y += a[k] ^ 1
            else:
                y += a[k]
        x = max(x, y)
print x

n=int(input())
nums=list(map(int,input().split()))
z=0
o=0
counts=[]
zeroes=[]
i=0
while i<len(nums):
    if nums[i]==0:
        z+=1
        zeroes.append(i)
    else:
        o+=1
    counts.append((z,o))
    i=i+1
max_o=o
if z!=0:
    for i in zeroes:
        for j in zeroes:
            if j>=i:
                zz=counts[j][0]-counts[i][0]+1
                oo=counts[j][1]-counts[i][1]
                if zz>oo:
                    new_o=zz+o-oo
                    if new_o>max_o:
                        max_o=new_o
else:
    max_o-=1
print(max_o)

if __name__ == '__main__':
    n = int(raw_input())
    bits = [int(num) for num in raw_input().split()]

    max_sum = 0
    for i in range(n):
        for j in range(i+1, n+1):
            max_sum = max(sum(bits[:i] + [1-bit for bit in bits[i:j]] + bits[j:]), max_sum)

    print max_sum

n = input()
x = map(int,raw_input().split())
arr = [0] * n
co,c = 0,0
if (x[0] == 0) :
	arr[0] = 1
else :
	co += 1
for i in range(1,n) :
	if (x[i] == 1) :
		co += 1
		if (arr[i - 1] > 0) :
			arr[i] = arr[i - 1] - 1
	else :
		arr[i] = arr[i - 1] + 1
if (co == n) :
	print n - 1
else :
	print co + max(arr)

import sys
n = int(input())
x = [int(x) for x in input().split()]
q = []
def check(l,i,j):
    count1 = 0
    count0 = 0
    count = 0
    for k in range(i,j+1):
        if l[k] == 1:
            count1 = count1+1
        else:
            count0 = count0+1
    for k in range(i):
        if l[k] == 1:
            count = count + 1
    for k in range(j+1,len(l)):
        if l[k] == 1:
            count = count + 1
    return count0 + count
if x == [1]*n:
    print(n-1)
    sys.exit(0)
if len(x) != 1:
    for i in range(len(x)):
        for j in range(i+1,len(x)):
            q.append(check(x,i,j))

    print(max(q))
else:
    print(1-x[0])

x=int(raw_input())
l=map(int, raw_input().split())
w=sum(l)
s=x-sum(l)
f=[]
g=[]
for i in range(x):
  for j in range(x):
    if i < j:
      f.append([l[0:i].count(1)+l[i:j+1].count(1)+l[j+1:].count(1),
                l[0:i].count(1)+l[i:j+1].count(0)+l[j+1:].count(1)
       ])
for i in range(len(f)):
  g.append(f[i][0])
  g.append(f[i][1])
if len(l) == 1:
  if l[0] == 0:
    print 1
  else:
    print 0
elif l.count(1) == x:
  print l.count(1)-1
else:
  print max(g)

n= int(input())

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

if t.count(1)==n:
    print(n-1)
elif t.count(0)==n:
    print(n)
else:

    u=0
    for k in range(n):
        for j in range(k+1,n+1):
            a=(t[k:j].count(0))+t[:k].count(1)+t[j:].count(1)
            if a>u:
                u=a

    print(u)

n = int(input())
ls = list(map(int, input().split()))
ary = [0 for i in range(n)]
# val = 0
# for i in range(n):
    # val += ls[i]
    # ary[i] = val
b = [1 if not x else -1 for x in ls]

s = 0
ma = -9e9
# for i in range(n):
    # for j in range(i, n):
        # ma = max(ma, ary[i] - ls[i] + (j - i + 1 - (ary[j] - ary[i] )) + ary[-1] - ary[j])
# print(ma)

mast = 0
maend = 0
st = 0
end = 0
# print(b)
for i in range(n):
    s += b[i]
    if s > ma:
        mast = st
        maend = i + 1
        ma = s

    if s < 0:
        s = 0
        st = i + 1

# print(ma, mast, maend)
print(sum(ls) + ma)

n = input()

arr = map(int, raw_input().strip().split(' '))

dp1 = [0]*n
dp2 = [0]*n

for i in range(n):
  if i == 0 and arr[0] == 1:
    dp1[0] = 0
    dp2[0] = 0
  elif i == 0 and arr[0] == 0:
    dp1[0] = 1
    dp2[0] = 0
  else:
    if arr[i] == 0:
      if dp1[i-1] > dp2[i-1]:
        dp1[i] = dp1[i-1] - dp2[i-1] + 1
        dp2[i] = 0
      else:
        dp1[i] = 1
        dp2[i] = 0
    else:
      dp1[i] = dp1[i-1]
      dp2[i] = dp2[i-1] + 1

answer = max(dp1)

if answer == 0:
    print n-1
else:

    print answer + arr.count(1)

n=int(input())
l=list(map(int,input().split()))
print(max([l[i:j+1].count(0)+(l[:i]+l[j+1:]).count(1) for i in range(n) for j in range(i,n)]))

result=0
n=int(input())
line=input()
line=line.split(sep=' ')
for k in range(n):
    line[k]=int(line[k])
for i in range(n):
    a=line[:]
    for j in range(i,n):
        a[j]=1-line[j]
        temp=sum(a)
        if temp>result:
            result=temp
print(result)

def f(x):
    return(1-x)
n=int(input())

q=list(map(int,input().split()))
if n==1:
    print(1-q[0])
else:
    s=[]

    for i in range(n-1):
        for j in range(i,n):
            a=list(map(f,q))
            t=0
            for k in range(i,j+1):
                t+=a[k]
            for m in range(0,i):
                t+=q[m]
            for h in range(j+1,n):
                t+=q[h]
            s.append(t)
    print(max(s))

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

def work(l,r,x):
    b = x
    for i in range(l,r+1):
        b[i] = 1-b[i];
    return sum(b)

ans = 0
for i in range(0,len(a)):
    for j in range(i,len(a)):
        ans = max(ans,work(i,j,a))
        work(i,j,a)
print ans

n = int(input())
l = list(map(int,input().split()))
print(max([l[i:j+1].count(0)+(l[:i]+l[j+1:]).count(1) for i in range(n) for j in range(i,n)]))

t = int(raw_input())
A = [int(x) for x in raw_input().split()]

B = [-1 if a==0 else 1 for a in A]

def findMin(A):
	N = len(A)
	T = [0]*N
	T[0] = A[0]
	for i in range(1, N):
		T[i] = A[i] + T[i-1]

	minsum = 0
	for i in range(0, N):
		for j in range(i, N):
			sum = T[j]-T[i]+A[i]
			if  sum < minsum:
				minsum = sum
			#print "(%s,%s) = %s, minsum=%s" %(i,j,sum,minsum)
	#print "Algorithm 2 : %s" % minsum
	return minsum

def min_subarray(A):
    min_ending_here = min_so_far = 0
    for x in A:
        min_ending_here = min(0, min_ending_here + x)
        min_so_far = min(min_so_far, min_ending_here)
    return min_so_far

sumA = sum(A)
if sumA == t:
	print t-1
else:
	print sumA + abs(min_subarray(B))

n = int(raw_input())
a = map(int, raw_input().split())

a_ = [-1] if a[0] else [1] # increments
s_ = [a_[0]]
count_1 = 1 if a[0] else 0

for i in range(n)[1:]:
    if a[i]:
        v = -1
        count_1 += 1
    else:
        v = 1

    if a_[-1]* v > 0:
        a_[-1] += v
        s_[-1] += v
    else:
        a_.append(v)
        s_.append(s_[-1] + v)

# now find the maximum sum of the sub string of a_
low = s_[0]
max = -1 if a[0] else s_[0]
for e in s_[1:]:
    if (e - low) > max:
        max = e - low
    elif e < low:
        low = e

print count_1 + max

n = input()
st = map(int, raw_input().split())

def main1():
    tot = 0
    maxn = -10000
    for i in xrange(0, n):
        if st[i] == 1:
            tot += 1
        for j in xrange(i, n):
            cnt0 = st[i:j+1].count(0)
            cnt1 = st[i:j+1].count(1)
            if cnt0 - cnt1 > maxn:
                maxn = cnt0 - cnt1
    res = tot + maxn
    print(res)

def main2():
    dp = [0] * (n + 1)
    stn = [-1 if st[i] == 1 else 1 for i in xrange(0, n)]
    dp[0] = stn[0]
    maxv = dp[0]
    for i in xrange(1, n):
        dp[i] = max(dp[i-1]+stn[i], stn[i])
        if dp[i] > maxv:
            maxv = dp[i]
    res = st.count(1) + maxv
    print(res)

if __name__ == "__main__":
    main2()

"""
Codeforces Round #191 (Div. 2)
327 A. Flipping Game

@author yamaton
@date 2015-08-05
      2015-09-22
      2015-11-04
"""

import itertools
import collections
import sys

def solve_bruteforce(xs):
    "O(N^3) solution"
    n = len(xs)
    if n == 1:
        return len(xs) - sum(xs)
    return max(sum(xs[:i]) + sum(xs[j:]) - sum(xs[i:j]) + (j - i)
               for (i, j) in itertools.combinations(n, 2))

def solve_slow(xs):
    "O(N^2) solution"
    n = len(xs)
    assert n > 0
    a = [1 if x == 0 else -1 for x in xs]
    b = collections.defaultdict(int)
    for i, acc in enumerate(itertools.accumulate(a)):
        b[i] = acc
    deltaS = max(b[j] - b[i] for i in range(-1, n) for j in range(i+1, n))
    if deltaS <= 0:
        return sum(xs) - 1
    else:
        return sum(xs) + deltaS

def solve_old(xs):
    "O(N) with DP"
    a = [1 if x == 0 else -1 for x in xs]
    b = itertools.accumulate(a)
    deltaS = 0
    min_so_far = 0
    for bk in b:
        deltaS = max(deltaS, bk - min_so_far)
        min_so_far = min(min_so_far, bk)

    if deltaS == 0:
        return sum(xs) - 1
    else:
        return sum(xs) + deltaS

def solve(xs):
    """ Maximum value contiguous subsequence problem """
    n = len(xs)
    a = [1 if x == 0 else -1 for x in xs]

    m = collections.defaultdict(int)
    maxval = 0
    for i in range(n):
        m[i] = max(m[i-1] + a[i], a[i])
        maxval = max(m[i], maxval)

    deltaS = maxval
    if deltaS == 0:
        return sum(xs) - 1
    else:
        return sum(xs) + deltaS

def test():
    xs = [0]
    assert solve(xs) == 1
    xs = [1]
    assert solve(xs) == 0
    xs = [0, 1, 0]
    assert solve(xs) == 2
    xs = [0, 0, 1, 0, 0]
    assert solve(xs) == 4
    xs = [0, 0, 0, 0]
    assert solve(xs) == 4
    xs = [1, 1, 1]
    assert solve(xs) == 2

def main():
    n = int(input())
    xs = [int(i) for i in input().strip().split()]
    assert len(xs) == n
    result = solve(xs)
    print(result)

if __name__ == '__main__':
    main()

n, a = int(input()), [int(x) for x in input().split()]
if not 0 in a: print(n-1); quit()
m = 0
for i in range(n):
    s = 0
    for row in a[i:]:
        row = 1 if row == 0 else -1
        s += row
        m = max(s, m)
print(m+sum(a))

n = input()
l = [int(x) for x in raw_input().split()]
n1 = sum(l)
res = -200
for i in range(len(l)):
	can = 0
	for j in range(i, len(l)):
		if l[j] == 0:
			can += 1
		else:
			can -= 1
		#print((i, j, can))
		if res < can:
			res = can
print(n1 + res)

x=int(input())
a=list(map(int,input().split()))
s=[]

for i in range(x):
    for j in range(i,x):
        l=0
        for k in range(x):
            if k>=i and k<=j:
                l+=(1-a[k])
            else:
                l+=a[k]
        s.append(l)

print(max(s))

n = int(input())
nums = [int(x) for x in input().split()]

if nums.count(1) == n:
    print(n - 1)
    exit()

count = nums.count(1)

for i in range(n):
    for j in range(i, n):
        count = max(count, nums[i:j + 1].count(0) - nums[i:j + 1].count(1) + nums.count(1))

print(count)

n=input();s=map(int,raw_input()[::2]);print max(sum(s)-2*sum(s[j:i])+i-j for i in range(n+1)for j in range(i))

n=int(input())
p=[int(i)for i in input().split()]
a=0
b=0
s=0
for i in p:
    a+=i
if n>1:
 for i in range(n-1):
    for j in range(i,n):
        for k in range(i,j+1):
            s+=p[k]
        if a+j-i+1-2*s>b:
            b=a+j-i+1-2*s
        s=0
else:
    if p[0]==1:
        b=0
    if p[0]==0:
        b=1
print(b)

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

p = []
for i in range(len(a)):
    if a[i]:
        p.append(-1)
    else:
        p.append(1)

s = a.count(1)

dp = [0 for i in range(len(a))]
dp[0] = p[0]
for i in range(1, len(a)):
    dp[i] = max(p[i], dp[i - 1] + p[i])

print(s + max(dp))

import sys

def flip_game(numbers):
    max_points = 0
    for i in range(len(numbers)):
        for j in range(i,len(numbers)):
            points = flip_and_count(numbers,i,j)
            max_points = points if points > max_points else max_points
    return max_points

def flip_and_count(numbers,i,j):
    flipped = numbers[:]
    for k in xrange(i,j+1):
        flipped[k] = flipped[k]^1
    count = 0
    for num in flipped:
        if num == 1:
            count = count+1
    return count

input = []
for i in range(2):
    input.append(sys.stdin.readline())
print flip_game([int(x) for x in input[1].split(" ")])

n = int(input())
line = input()
line = [int(i) for i in line.split()]
output = 0
for i in range(n):
    text = line[:]
    for j in range(i,n):
        text[j] = 1 - text[j]
        output = max(sum(text),output)
if n == 1:
    output = 1 - line[0]
print(output)

# import math
# import bisect
import sys
# from collections import OrderedDict
input = sys.stdin.readline
def inp():
	return(int(input()))
def inlt():
	return(list(map(int,input().split())))
def insr():
	s = input()
	return(s[:len(s)-1])
def invr():
	return(map(int,input().split()))
# list1, list2 = zip(*sorted(zip(list1, list2)))
n = inp()
A = inlt()
def maxSubArraySum(a,size):

	max_so_far = 0
	max_ending_here = 0

	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if (max_so_far < max_ending_here):
			max_so_far = max_ending_here

		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far
B = []
for i in range(n):
	if A[i] == 1:
		B.append(-1)
	else:
		B.append(1)
a = sum(A)
b = maxSubArraySum(B,n)
if a == n:
	print(n-1)
else:
	print(a+b)

if __name__=='__main__':
    N = int(raw_input())
    inp = raw_input()
    arr = inp.split()
    t1=0
    ans = 0
    for i in arr:
        if i=='1':
            t1+=1
    for i in range(N):
        for j in range(N):
            if j>=i:
                rev = 0
                for k in range(i,j+1):
                    if arr[k]=='0':
                        rev+=1
                    else:
                        rev-=1
                ans = max(ans,t1+rev)
    print ans

n = int(input())
lst = [int(i) for i in input().split()]
output = []
for i in range(n):
    for j in range(i+1,n+1):
        total = lst[:i].count(1)+lst[i:j].count(0)+lst[j:].count(1)
        output.append(total)
print(max(output))

n=int(raw_input())
a= map(int,raw_input().split())
lis=[]
for i in xrange(n):
	if a[i]==0:
		lis.append(1)
	else:
		lis.append(-1)
val=0
for i in xrange(n):
	lol=0
	for j in range(i,n):
		lol+=lis[j]
		if lol>val:
			val=lol
			x=i
			y=j
#print x,y
if n==1:
	if a[0]==1:
		print "0"
	else:
		print "1"
else:
	if val==0:
		print n-1
	else:
		count=0
		for i in xrange(x):
			if lis[i]==-1:
				count+=1
		for i in range(y+1,n):
			if lis[i]==-1:
				count+=1
		for i in range(x,y+1):
			if lis[i]==1:
				count+=1
		print count

from copy import deepcopy
n =int(input())
s=[int(s) for s in input().split()]
t=[]
p = deepcopy(s)
for i in range(n):
    for j in range(i,n):
        p[j]=1-p[j]
        t.append(sum(p))
    p = deepcopy(s)
print(max(t))

n = int(input())
a = [int(x) for x in input().split()]
count = a.count(1)
m = 0
if len(a) == a.count(1):
    if len(a) == 1:
        print(0)
    else:
        print(len(a)-1)
else:

    for i in range(n):
        for j in range(i,n):
            if a[j] == 0:
                one = a[i:j].count(1)
                zer = a[i:j].count(0)
                if zer > one:
                    maxi = zer-one
                    if maxi > m:
                        m = maxi

    print(m+count+1)

n = int(raw_input())
coins = [int(i) for i in raw_input().split()]
flipped = []
for i in range(n):
    if coins[i] == 1:
        flipped.append(-1)
    else:
        flipped.append(1)
max_so_far = flipped[0]
curr_max = flipped[0]
for i in range(1, n):
    curr_max = max(curr_max + flipped[i], flipped[i])
    max_so_far = max(max_so_far, curr_max)
print max_so_far + sum(coins)

number=int(raw_input())
game=raw_input()
game=game.split(' ')
edinic=game.count('1')
maxim=1
for i in range(len(game)):
    if game==['1']:
        maxim=0
    for m in range(i,len(game)):
        curr_result=edinic
        for k in game[i:m+1]:
             if k=='0':
                 curr_result+=1
             else:
                 curr_result-=1
        if curr_result>maxim:
            maxim=curr_result
print maxim

n=int(raw_input())
str=raw_input()
t=[]
initial=0
sum=0
for i in range(0, n):
    t.append(int(str.split(" ")[i]))
for i in range(0,n):
    sum=sum+t[i]
if sum==n:
    print n-1
elif sum==0:
    print n
else:

    for i in range(0, n - 1):
        for j in range(i + 1, n+1):
            t1 = []
            for k in range(i, j):
                t1.append(t[k])
            sum = 0
            for k in range(0, len(t1)):
                if t1[k] == 0:
                    sum += 1
                elif t1[k] == 1:
                    sum -= 1
            if sum > initial:
                initial = sum
                imax = i
                jmax = j
    for i in range(imax, jmax):
        t[i] = 1 - t[i]
    total = 0
    for i in range(0, n):
        total = total + t[i]
    print total

"""
sum0=[]
sum0.append(1)
j=0
for i in range(0,n-1):
    if t[i]==t[i+1]:
        sum[j]+=1
    else:
        j+=1
        sum.append(1)
print sum
"""

def flip(l,a,b):
    for i in range(a,b):
        if l[i] == 1:
            l[i] = 0
        else:
            l[i] = 1

    return l

def solver():
    n = input()
    num = map(int, raw_input().split())
    maxim = 0

    if not (0 in num):
        print n-1
        return

    if n == 1:
        if num[0] == 0:
            print 1
        else:
            print 0

        return

    for i in range(0,n):
        for j in range(i,n+1):
            new_b = num[:]
            new_b = flip(new_b,i,j)
            maxim = max(maxim,new_b.count(1))
            #print new_b

    print maxim

if __name__ == "__main__":
    solver()

a = raw_input()
b = [int(i) for i in raw_input().split(' ')]
s = sum(b)
res = []
for i in range(int(a)):
    if b[i] == 0:
        res.append(1)
    else:
        res.append(-1)
RES = [res[0]]
for i in range(1,int(a)):
    r = max(RES[-1]+res[i],res[i])
    RES.append(r)
m = max(RES)
print s+m

n = int(input())
a = [int(a_i) for a_i in input().split()]
max_ones = 0

for i in range(n):
    for j in range(i, n):
        temp = sum(a) - a[i:j+1].count(1) + a[i:j+1].count(0)
        if max_ones < temp:
            max_ones = temp

print(max_ones)

num = eval(input())
data = [eval(i) for i in input().split()]
count = data.count(1)
add = -100
for i in range(num):
    for j in range(i+1, num+1):
        k = data[i:j].count(0) - data[i:j].count(1)
        add = max(add, k)
print(count + add)

#ref: http://blog.csdn.net/catglory/article/details/45950683
n = int(input())
a = [int(i) for i in input().split()]

cnt1 = sum(a)

mx = 0; cnt0 = 0
for i in a:
        if i==0 :
            cnt0 += 1
            if cnt0 > mx :
                mx = cnt0
        elif cnt0>0:
             cnt0 -= 1   # 1 will affect cnt0 value -1

if mx==0: mx -= 1  # at least flipping once if no zero
print(cnt1 + mx)

I0 = lambda :map(int,input().split())
I1 = lambda :int(input())
I2 = lambda :list(map(int,input().split()))
#####################################################
n = I1()
a = I2()
M=-1

one = a.count(1)
for i in range(n):
    for j in range(i,n):
        zero = a[i:j+1].count(0)
        one1 = j+1-i-zero
        M = max(M,one-one1+zero)
print(M)

n = int(input())
lst = list(map(int,input().split()))
lst2 = []
mega_cnt = 0
for i in lst:
    if i == 1:
        mega_cnt += 1
for i in range(n):
    for j in range(i+1,n+1):
        a = lst[i:j]
        #print(a)
        cnt = 0
        cnt2 = 0
        for b in a:
            if b == 1:
                cnt += 1
            else:
                cnt2 += 1
        yo = cnt2 - cnt
        lst2.append(yo)
print(mega_cnt+max(lst2))

n=int(input())
arr=list(map(int,input().split()))
ans=0
for i in range(n):
    for j in range(i,n):
        count=0
        for k in range(n):
            if k<=j and k>=i:
                count+=1-arr[k]
            else:
                count+=arr[k]
        ans=max(count,ans)
print(ans)

n = int(input())
list = input().split()
list = [int(i) for i in list]
ls = []

for i in list:
    if i == 1:
        ls.append(-1)
    else:
        ls.append(1)
thisSum = 0
maxSum = 0
for i in ls:
    thisSum += i
    if thisSum > maxSum:
        maxSum = thisSum
    elif thisSum < 0:
        thisSum = 0
if maxSum == 0:
    print(maxSum + sum(list) - 1)
else:
    print(maxSum + sum(list))

# coding = utf-8
n = input()
a = map(int,raw_input().split())
b = []
count = 0
for i in a:
	if i == 1:
		b.append(-1)
		count += 1
	else:
		b.append(1)
sum = 0
max = -2
for j in b:
	sum += j
	if sum>max:
		max = sum
	if sum < 0:
		sum = 0
print max+count

l=int(input())
a=input().split()
b=[]
for i in range(l):
    for j in range(i+1,l+1):#从i+1开始枚举到l

        b.append(a.count("1")-j+i+2*a[i:j].count("0"))
        #a中1的数目+i到j中0个数的两倍+i-j
print(max(b))

#!/usr/bin/env python3

def main():

    from itertools import accumulate

    n = int(input())
    arr = [int(x) for x in input().split()]
    ones = list(accumulate(arr))
    ans = 0

    ones_inside = lambda i, j: ones[j] - ones[i-1] if i else ones[j]
    ones_outside = lambda i, j: ones[n-1] - ones_inside(i, j)

    for i in range(0, n):
        for j in range(i, n):
            partial = ones_outside(i,j) + (j-i + 1 - ones_inside(i,j))
            ans = max(ans, partial)

    print(ans)

if __name__ == "__main__":
    main()

def ni():
    return int(raw_input())

def nis():
    return map(int, raw_input().split())

def si():
    return raw_input()

n = ni()

a = nis()

max_val = None
start = end = 0
current_max = 0
current_start = 0
ones = 0

for i in range(n):
    val = a[i]
    if val:
        current_max -= 1
        ones += 1
    else:
        current_max += 1

    if max_val is None or current_max > max_val:
        max_val = current_max
        start = current_start
        end = i

    if current_max < 0:
        current_max = 0
        current_start += 1

print ones + max_val

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

maxx= (sum(a)+1)%(n+1)

for i in xrange(n):
  for j in xrange(i+1,n+1):
    summ = sum(a)-(2*sum(a[i:j]))+len(a[i:j])
    maxx = max(summ,maxx)

print maxx

n = int(input())
lst = list(map(int,input().split()))
lst2 = []
mega_cnt = 0
for i in lst:
    if i == 1:
        mega_cnt += 1
for i in range(n):
    for j in range(i+1,n+1):
        a = lst[i:j]
        cnt = 0
        cnt2 = 0
        for b in a:
            if b == 1:
                cnt += 1
            else:
                cnt2 += 1
        yo = cnt2 - cnt
        lst2.append(yo)
print(mega_cnt+max(lst2))

n=int(input())
l=list(map(int,input().split()))
print(max([l[i:j+1].count(0)+(l[:i]+l[j+1:]).count(1) for i in range(n) for j in range(i,n)]))

n = int(raw_input())
a = map(int,raw_input().split())
ans = 0;
for i in range(n):
	for j in range(i,n):
		b = a[:]
		temp = 0
		for k in range(i,j + 1):
			b[k] = 1 - b[k]
		for k in range(n):
			temp += b[k]
		ans = max(ans,temp)
print ans

n = input()
l = map(int, raw_input().split())
res = 0; maxi = 0
for i in l:
    res = max(0, res+(1-2*i))
    maxi = max(maxi, res)
print l.count(1) + (maxi if maxi > 0 else -1)

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 20.07.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n=ii()
    l=li()

    tot=0
    for i in range(n):
       tot+=l[i]

    dp=[0]*n
    for i in range(n):
        if l[i]==1:
            l[i]=-1
        else:
            l[i]=1

    m=l[i]
    c=l[i]
    dp[0]=l[0]

    for i in range(1,n):
        dp[i]=max(dp[i-1]+l[i],l[i]) #Kadane Algo

        #c=max(l[i],c+l[i])
        #m=max(m,c)

    m=max(dp)

    print(tot+m)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

def main():
    n = int(input())
    l = list(map(int, input().split()))
    res = sum(l)
    a = b = 0
    for i, x in enumerate(l):
        l[i] = b - a
        a += x
        b += 1 - x
    l.append(b - a)
    hi, lo = max(((i, j) for i in range(n + 1) for j in range(i + 1)), key=lambda _: l[_[0]] - l[_[1]])
    if hi == lo:
        res -= 1
    else:
        res += l[hi] - l[lo]
    return res

print(main())

n=int(input())
a=[int(i) for i in input().split()]
s=sum(a)
d=[0]
t=list(range(0,int(len(a)+1)))
if s==int(len(a)):
	if n==1 :
		for value in a:
			if int(value)==1:
				print('0')
			else:
				print('1')
	else:
		print(int(s-1))
else:
	for i in t:
		for j in t:
			if i>=j:
				pass
			else:
				c=sum(a[i:j])
				b=[]
				for value in a[i:j]:
					if int(value)==1:
						value=0
						b.append(value)
					else:
						value=1
						b.append(value)
				r=int(sum(b)-c)
				d.append(r)
	g=max(d)
	print(int(s+g))

n = int(input())
lst = [int(x) for x in input().split()]

cur_num = sum(x==1 for x in lst)
def trans(x):
    return -1 if x==1 else 1
sum_lst = [0]
for el in lst:
    sum_lst.append(sum_lst[-1]+trans(el))

#we need all sums from i inclusive to j exclusive, 0<=i<j<n
#sum_lst[j]-sum_lst[i] is the sum i+1 to j inclusive
max_sum = -100
for i in range(n):
    for j in range(i+1,n+1):
        cur = sum_lst[j]-sum_lst[i]
        if cur>max_sum:
            max_sum = cur
print(max_sum+cur_num)

n = int(raw_input())
a = [int(_) for _ in raw_input().split()]

maxcnt = -1

for i in range(n):
    for j in range(i, n):
        cnt = 0
        for k in range(i):
            cnt += a[k]
        for k in range(j+1, n):
            cnt += a[k]
        for k in range(i, j+1):
            if a[k] == 0:
                cnt += 1
        if cnt > maxcnt:
            maxcnt = cnt

print maxcnt

n=int(input())
nums=list(map(int,input().split()))
maxn=-1
if(n==1):
    print(n-sum(nums))
    exit(0)
for i in range(n):
    for j in range(i,n):
        s=sum(nums[:i])+j-i+1-sum(nums[i:j+1])+sum(nums[j+1:])
        maxn=max(maxn,s)
print(maxn)

n = int(input())
line = input()
line = [int(i) for i in line.split()]
output = 0
for i in range(n):
    text = line[:]
    for j in range(i,n):
        text[j] = 1 - text[j]
        output = max(sum(text),output)
if n == 1:
    output = 1 - line[0]
print(output)

n=input();s=map(int,raw_input()[::2]);print max(sum(s)-2*sum(s[j:i])+i-j for i in range(n+1)for j in range(i))

n=int(input())
x=input().split()
a=[]
for i in x:
	a.append(int(i))
q,w,e,r = 0,0,0,-1
for i in range(n):
  q+=a[i]
  w+=1-a[i]*2
  r=max(r,w-e)
  e=min(w,e)
ans = q+r
print(ans)
'''

n=int(input())
x=input().split()
a=[]
for i in x:
	a.append(int(i))
print(max((sum(a)-2)*sum(a[i:j])+j-i for i in range(n)for j in range(i+1,n+1)))

'''

'''a=[]
flag=0
ans=0
for k in (0,1,1):
	print(k)
for i in x:
	a.append(int(i))
flag1=0
for i in range(n):
	if(a[i]==1):
		flag1+=1
for i in range(0,n,1):
	for j in range(i,n,1):
		flag=0
		if(i!=j):
			for k in range(i,j):
				if(a[k]==0):
					flag+=1
					ans=max(ans,flag)
if(ans==0):
	print(0)
else:
	print(ans+flag1)'''

read_ints = lambda : map(int, raw_input().split())

def main():
    n = input()
    a = read_ints()
    c = a.count(1)
    ans = 0
    for i in range(n):
        for j in xrange(i, n):
            t = c
            for k in xrange(i, j+1):
                if a[k] == 1:
                    t -= 1
                else:
                    t += 1
            if t > ans:
                ans = t
    print ans

if __name__ == '__main__':
    main()

n = int(input())

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

left = 0
right = 0
if 0 not in a:
    print(n-1)
else:
    maxi = 0
    for i in range(n):
        for j in range(i,n):
            count = 0
            for k in range(n):
                if i<=k and k<=j:
                    if a[k] == 0:
                        count+=1
                else:
                    if a[k] == 1:
                        count+=1
            maxi = max(maxi , count)
    print(maxi)

a = raw_input()
b = [int(i) for i in raw_input().split(' ')]
s = sum(b)
res = []
for i in range(int(a)):
    if b[i] == 0:
        res.append(1)
    else:
        res.append(-1)
RES = [res[0]]
for i in range(1,int(a)):
    r = max(RES[-1]+res[i],res[i])
    RES.append(r)
m = max(RES)
print s+m

n = input()
a = map(int, raw_input().split(' '))

maxi = 0
for i in range(n):
    for j in range(i, n):
        c = a[0:i:].count(1) + a[i:j+1:].count(0) + a[j+1:n:].count(1)
        if c > maxi:
            maxi = c
print maxi

n=int(raw_input())
arr=[int(i) for i in raw_input().split()]
no=0
for i in range(n):
    if arr[i]==1:
        no+=1
for i in range(n):
    if arr[i]==0:
        arr[i]=1
    else:
        arr[i]=-1
me,ms=0,0
for i in range(n):
        me=max(0,me+arr[i])
        ms=max(ms,me)
if ms==0:
    ms=-1
print ms+no

n = int(input())
a = [int(x) for x in input().split()]
count = a.count(1)
m = 0
if len(a) == a.count(1):
    if len(a) == 1:
        print(0)
    else:
        print(len(a)-1)
else:

    for i in range(n):
        for j in range(i,n):
            if a[j] == 0:
                one = a[i:j].count(1)
                zer = a[i:j].count(0)
                if zer > one:
                    maxi = zer-one
                    if maxi > m:
                        m = maxi

    print(m+count+1)

n = int(input())
line = input().split()
x = 0
c = 0
output = 0
for i in range(n):
    if int(line[1])==1:
        c =c +1
for i in range(n):
    for t in range(i+1,n):
        for j in range(i,t):
            if int(line[j])==1:
                x = x+1
        s = t-i-2*x
        output = max(output,s)
        x = 0
output = output +c
if c == len(line):
    output = output -1
print(output)

# You lost the game.
n = int(input())
L = list(map(int, input().split()))
T = [0 for _ in range(n)]
T[0] = 1-L[0]
for i in range(1,n):
    T[i] = T[i-1]+1-L[i]
print(T[n-1])

n=int(input())
s=input().split()

M=[[0]*n for _ in range(n)]

num=0
for i in range(n):
    if s[i]=='0':
        M[i][i]=1
    else:
        M[i][i]=-1
        num+=1
Max=-1

for j in range(n-1,-1,-1):
    for i in range(j-1,-1,-1):
        if s[i]=='1':
            M[i][j]=M[i+1][j]-1
        else:
            M[i][j]=M[i+1][j]+1
        Max=max(M[i][j],Max)

print(num+Max)

num = eval(input())
data = [eval(i) for i in input().split()]
count = data.count(1)
benchmark = -1
for i in range(num):
    for j in range(i, num):
        k = data[i:j].count(0) - data[i:j].count(1)
        benchmark = max(benchmark, k)
count = count + benchmark
print(count)

n = int(input())
mas = [int(x) for x in input().split()]
if n == 1:
	if mas[0] == 1:
		print(0)
		raise SystemExit
	else:
		print(1)
		raise SystemExit
if all(mas) == True:
	print(n-1)
	raise SystemExit
first = mas.index(0)
mas.reverse()
last = n - mas.index(0)
mas.reverse()
alkol1 = mas.count(1)
kol1 = mas[first:last].count(1)
kol0 = mas[first:last].count(0)
print(alkol1-kol1+kol0)

n = int(input())
a = input()
A = list(map(int,list(a.split())))
for i in range(n):
    if A[i] == 0:
        A[i] = -1
table = [0]*(n)
table[0] = A[0]
for  i in range(1,n):
    table[i] = min(A[i],A[i]+table[i-1])
c = 0
d = 0
m = min(table)
i = 0
while(i<n):
    if table[i]>0:
        c = c+1
        i = i+1
    elif table[i] == m:
        j = i+1
        while(j<n):
            if A[j] == 1:
                c = c+1
            j = j+1
        break
    else:
        if A[i] == 1 and table[i]<0:
            d = d+1
        i = i+1
print(c-m+d)

from copy import deepcopy
n = int(input())
line = input().split()
Max = deepcopy(line)
copy = deepcopy(line)
for i in range(n-1):
    for j in range(i+1,n):
        copy = deepcopy(line)
        for k in range(i,j+1):
            if copy[k] == '0':
                copy[k] = '1'
            else:
                copy[k] = '0'
        if copy.count('1') > Max.count('1'):
            Max = deepcopy(copy)
print(Max.count('1'))

def main():

    n = int(raw_input())

    if n ==1:

        nn = int(raw_input())
        return 1

    data = [int(s) for s in (raw_input()).split()]

    answer = max([((i,j), 2*(data[i:j].count(0)) - j +i +data[:i].count(1) +data[j:].count(1) ) for i in range(n) for j in range(i,n)]  , key = lambda x: x[1])

    #print answer
    return answer[1]

if __name__ =="__main__":

    print main()

n=int(input(""))
l=list(map(int,input().split()))
max1=0
for i in range(0,len(l)):
    count=0
    if(l[i]==1):
        count=1
        for j in range(i+1,len(l)):
            if(l[j]==0):
                count+=1
            elif(l[i]==1):
                count+=1
                if(max1<count):
                    max1=count
                break
print(max1)

def f(x):
    return(1-x)
n=int(input())

q=list(map(int,input().split()))
if n==1:
    print(q[0])
else:
    s=[]

    for i in range(n-1):
        for j in range(i+1,n):
            a=list(map(f,q))
            t=0
            for k in range(i,j+1):
                t+=a[k]
            for m in range(0,i):
                t+=q[m]
            for h in range(j+1,n):
                t+=q[h]
            s.append(t)
    print(max(s))

n = int(raw_input())
ar = map(int,raw_input().split())
pr,cr = ar[0],-1
mx = 0
tot = 0
n1 = 0
if ar[0]==1:
    n1 = 1
tot = 1
if ar.count(1)==n:
    print n-1

else:
    for i in range(1,n):
        pr = ar[i-1]
        cr = ar[i]
        if pr==1 and cr==0:
            mx = max(mx,tot)
            tot = n1 + 1
        else:
            tot += 1

        if cr==1:
            n1 += 1
        else:
            n1 = 0

    mx = max(mx,tot)
    print mx

import sys

n = int(sys.stdin.readline())

string = sys.stdin.readline().strip().split(' ')

num_ones = 0
for elem in string:
    if elem == '1':
        num_ones += 1

mat = []

for i in range(n):
    row = [0]*n
    mat.append(row)
result = 0
for i in range(n):
    mat[i][i] = num_ones + 1 if string[i] == '0' else num_ones - 1
    if result < mat[i][i]:
        result = mat[i][i]

for j in range(1,n):
    for diff in range(1,n):
        mat[j-diff][j] = mat[j-diff+1][j] + 1 if string[j-diff] == '0' else mat[j-diff+1][j] - 1
        if result < mat[j-diff][j]:
            result = mat[j-diff][j]

print result

t = int(raw_input())
A = [int(x) for x in raw_input().split()]

B = [-1 if a==0 else 1 for a in A]

def findMin(A):
	N = len(A)
	T = [0]*N
	T[0] = A[0]
	for i in range(1, N):
		T[i] = A[i] + T[i-1]

	minsum = 0
	for i in range(0, N):
		for j in range(i, N):
			sum = T[j]-T[i]+A[i]
			if  sum < minsum:
				minsum = sum
			#print "(%s,%s) = %s, minsum=%s" %(i,j,sum,minsum)
	#print "Algorithm 2 : %s" % minsum
	return minsum

minval = findMin(B)
print sum(A) + abs(minval)

n = int(raw_input())
a = map(int, raw_input().split())

a_ = [-1] if a[0] else [1] # increments
s_ = [a_[0]]
count_1 = 1 if a[0] else 0

for i in range(n)[1:]:
    if a[i]:
        v = -1
        count_1 += 1
    else:
        v = 1

    if a_[-1]* v > 0:
        a_[-1] += v
        s_[-1] += v
    else:
        a_.append(v)
        s_.append(s_[-1] + v)

# now find the maximum sum of the sub string of a_
low = s_[0]
max = -1
for e in s_[1:]:
    if (e - low) > max:
        max = e - low
    elif e < low:
        low = e

print count_1 + max

x=int(raw_input())
l=map(int, raw_input().split())
w=sum(l)
s=x-sum(l)
f=[]
g=[]
for i in range(x):
  for j in range(x):
    if i!=j:
      f.append([l[0:i].count(1)+l[i:j+1].count(1)+l[j+1:].count(1),
                l[0:i].count(1)+l[i:j+1].count(0)+l[j+1:].count(1)
       ])
for i in range(len(f)):
  g.append(f[i][0])
  g.append(f[i][1])
if len(l) == 1:
  if l[0] == 0:
    print 1
  else:
    print 0
else:
  print max(g)

# Lang: pypy3.6-v7.1.0-win32\pypy3.exe
# Problem Name: FlippingGame
# Problem Serial No: 327
# Problem Type: A
# Problem Url: https://codeforces.com/problemset/problem/327/A
# Solution Generated at: 2019-05-30 22:19:12.036155 UTC
n = int(input())
arr = list(map(lambda x: -1 if int(x) > 0 else 1, input().split()))
cn_1 = 0
local_optimal, global_optimal = arr[0], arr[0]
for idx in range(1, n):
    num = arr[idx]
    local_optimal = max(num, local_optimal + num)
    global_optimal = max(local_optimal, global_optimal)
    if num == -1:
        cn_1 += 1
print(global_optimal + cn_1)

# Accepted

n = int(input())
ls = list(map(int, input().split()))
ary = [0 for i in range(n)]
# val = 0
# for i in range(n):
    # val += ls[i]
    # ary[i] = val
b = [1 if not x else -1 for x in ls]

s = 0
ma = -9e9
# for i in range(n):
    # for j in range(i, n):
        # ma = max(ma, ary[i] - ls[i] + (j - i + 1 - (ary[j] - ary[i] )) + ary[-1] - ary[j])
# print(ma)

mast = 0
maend = 0
st = 0
end = 0
for i in range(n):
    s += b[i]
    if s > ma:
        mast = st
        maend = i
        ma = s

    if s < 0:
        s = 0
        st = i + 1

print(sum(ls[:mast]) + ma + sum(ls[maend:]))

from sys import stdin

def main():
    n = int(stdin.readline().strip())
    l0 = list(map(int, stdin.readline().strip().split()))
    if sum(l0) == n > 0:
        return n - 1
    x, l = 0, [0]
    for y in l0:
        x += y * 2 - 1
        l.append(x)
    f = l.__getitem__
    lo = max(range(n + 1), key=f)
    hi = min(range(lo, n + 1), key=f)
    return sum(l0) + hi - lo - sum(l0[lo:hi])

print(main())

#stdin.readline()
#int(stdin.readline())
#stdout.write()
#raw_input()
#map(int,raw_input().split())
#map(int,stdin.readline().split())
def main():
    n=input()
    a=map(int,stdin.readline().split())
    z=0
    t=0
    for i in xrange(n):
        if a[i]==0:
            t+=1
        else:
            z=max(z,t)
            t=0
    z=max(z,t)
    if z==0:
        z=-1
    print sum(a)+z
if __name__ == "__main__":
    from sys import stdin, stdout
    main()

n = int(input())
a = [int(x) for x in input().split()]
b = sum(a)
if n == 1:
	print(1 - a[0])
elif b == n:
	print(n)
else:
	for i in range(n):
		for j in range(i, n):
			b = max(b, 1 + j - i - sum(a[i:j]) + sum(a[:i]) + sum(a[j:]))
	print(b)

n = int(input())
arr = input().split()
score = arr.count('1')

if '0' in arr:
	start = arr.index('0')
	end = n-1-arr[::-1].index('0')
	diff = 0
	for i in range(start, end):
		for j in range(start+1, end+1):
			temp = arr[i:j+1]
			zeroes = temp.count('0')
			ones = temp.count('1')
			if zeroes>ones and zeroes-ones>diff:
				diff = zeroes-ones
	print(diff+score)

else:
	print(n-1)

n=int(input())
x=input().split()
y=[0for i in range(n)]
S,s,m=0,0,0
if n==1:
    print(1-int(x[0]))
else:
 for i in range(n):
    x[i]=int(x[i])
    S+=x[i]
 for i in range(n):
    for j in range(i,n):
        t=0
        for k in range(i-1,j+1):
            t+=x[k]
        s=j-i+2-2*t
        if m<s:
            m=s
 print(m+S)

import itertools as itls
import operator as op
from collections import Counter

def inputarray(func=int):
    return map(func, input().split())

def diff(v, x = 0):
    v = iter(v)
    while True:
        try:
            y = next(v)
            yield y - x
            x = y
        except StopIteration:
            return

# -------------------------
# -------------------------

N = int(input())
A = list(inputarray())

R = [0] + [None]*len(A)
S = [0] + [None]*len(A)
P = [0] + list(itls.accumulate(A))

for i in range(len(A)):
    if A[i] == 0:
        R[i + 1] = max(R[i], P[i]) + 1
        S[i + 1] = max(S[i], R[i])
    else:
        R[i + 1] = max(R[i], P[i + 1])
        S[i + 1] = max(S[i], R[i]) + 1

print(max(R[-1], S[-1]))

n = int(input())
x = [int(x) for x in input().split()]
q = []
def check(l,i,j):
    count1 = 0
    count0 = 0
    count = 0
    for k in range(i,j+1):
        if l[k] == 1:
            count1 = count1+1
        else:
            count0 = count0+1
    for k in range(i):
        if l[k] == 1:
            count = count + 1
    for k in range(j+1,len(l)):
        if l[k] == 1:
            count = count + 1
    return count0 - count1 + count
if len(x) != 1:
    for i in range(len(x)):
        for j in range(i+1,len(x)):
            q.append(check(x,i,j))

    print(max(q))
else:
    print('1')

n = int(input())
lst = list(map(int,input().split()))
best = 0
no_of_ones = 0
for i in lst:
    if i == 1:
        no_of_ones += 1
for i in range(n):
    for j in range(i+1,n+1):
        arr = lst[i:j]
        x = 0
        y = 0
        for b in arr:
            if b == 1:
                y += 1
            else:
                x += 1
        best = max(best,x-y)
print(no_of_ones+best)

n = int(input())
l = [int(k) for k in input().split()]
output = []
b=c = 0
while b < n:
    while c <= n:
        l_ = []
        for i in range(n):
            if i in range (b,c+1):
                l_.append(1-l[i])
            else:
                l_.append(l[i])
        output.append(sum(l_))
        c +=1
    c = 0
    b += 1
x = max(output)
y = sum(l)
print(max(x,y))

n=int(input())
line=input().split()
s=0
for i in range(n):
    if int(line[i])==0:
        s=s+1
if s%2==0:
    print(n)
else:
    print(n-1)

n = int(input())
a = list(map(int, input().split()))
s = 0
v = []
for i in a:
    s += i
    if i:
        v.append(-1)
    else:
        v.append(1)
x = v[0]
ans = x
mn = x
for i in range(1, len(v)):
    x += v[i]
    ans = max(ans, x - mn)
    mn = min(mn, x)
print(s + ans)

n=int(input())
lt=list(map(int,input().split()))
a=[]
for i in range(0,n):
    if lt[i]==1:
        print (len(lt)-1)
    else:
        for i in range(0,n):
            for j in range(i+1,n):

                for x in range(i,j):
                    lt[x]=1-lt[x]
                a.append(lt.count(1))

                for x in range(i,j):
                    lt[x]=1-lt[x]
        print (max(a))

n=int(input())
arr=list(map(int,input().split()))
_max=0
start0=-1
end0=-1
i=0
flag=0
while i<n:
    if arr[i]==1:
        i+=1
    else:
        max_zeroes=1
        start=i
        while (i+1)<n and arr[i+1]==0:
            max_zeroes+=1
            i+=1
        end=i
        if max_zeroes>_max:
            start0=start
            end0=end
            _max=max_zeroes
        i+=1
if start0==-1 and end0==-1:
    print(0)
else:
    if start0==0 and end0==n-1:
        print(n)
    elif start0==0 or end0==n-1:
        print(end0-start0+1+1)
    else:
        print(end0-start0+1+2)

n=int(input())
arr=list(map(int,input().split()))
b=[]
for i in range(n):
    if arr[i]==0:
        b.append(1)
    else:
        b.append(-1)
pref_sum=[]
_sum=0
for i in range(n):
    _sum+=b[i]
    pref_sum.append(_sum)
_max=0
start=-1
end=-1
for i in range(n):
    for j in range(i+1,n):
        if pref_sum[j]-pref_sum[i]+b[i]>_max:
            start=i
            end=j
if start==-1:
    if n==1:
        if arr[i]==0:
            print(1)
        else:
            print(0)
    else:
        print(0)
elif start==0 and end==j:
    print(n)
elif start==0 or end==j:
    print(end-start+1+1)
else:
    print(end-start+1+2)

# Iahub got bored, so he invented a game to be played on paper.

# He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.

# The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.

# Input
# The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1.

# Output
# Print an integer — the maximal number of 1s that can be obtained after exactly one move.

# Examples
# inputCopy
# 5
# 1 0 0 1 0
# outputCopy
# 4
# inputCopy
# 4
# 1 0 0 1
# outputCopy
# 4
# Note
# In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].

# In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
n = int(input())
arr = [-1 if x=="1" else 1 for x in input().split()]
global_max = 0
current_max = 0
end = 0
while end<n:
    current_max += arr[end]
    if current_max<0:
        current_max=0
    if global_max<current_max:
        global_max = current_max
    end+=1
for i in arr:
    if i==-1:
        global_max+=1
print(global_max)

n=input()
a=map(int,raw_input().split())
m = 0
for i in range(0,n):
	for j in range(i,n+1):
		db = a[:i].count(1) + a[i:j].count(0) + a[j:n].count(1);
		if (m<db):
			m = db
if (a == [1]):
	m = 0
print m

import sys
from math import sqrt
input = sys.stdin.readline

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

n = int(input())
bits = list(map(int,input().split()))
res=-1
for i in range(n):
    for j in range(i+1,n):
        temp = bits.copy()
        for k in range(i,j+1):
            temp[k] = 1-temp[k]
        res = max(temp.count(1),res)
if n == 1:
    res = 1-bits[0]
print(res)

import math
def main():
    n = int(input())
    arr = list(map(int,input().split()))

    if n == 1:
        print(0 if arr[0] == 1 else 1)
        return
    ans = 0
    for i in range(len(arr) - 1):
        for j in range(i + 1,len(arr)):
            temp = arr + [9]
            for k in range(i,j + 1):
                if temp[k] == 0:
                    temp[k] = 1
                else:
                    temp[k] = 0
            ans = max(ans, temp.count(1))
    print(ans)

main()

a=int(input())
b=[int(i) for i in input().split()]
c=[]
for i in range(1,a):
    for k in range(i+1,a):
        x=b[0:i]
        y=b[i:k]
        z=b[k:a]
        f=[]
        for l in range(i,k):
            f.append(1-b[l])
            m=sum(x)+sum(f)+sum(z)
            c.append(m)
if c!=[]:
    print(max(c))
else:
    print("1")

n = int(input())
x = list(map(int,input().split()))
y = []
for i in range(1, n + 1):
    for j in range(i, n + 1):
        t = x[i:(j + 1)].count(0) - x[i:(j + 1)].count(1)
        s = x[0:i].count(1) + x[j:(n + 1)].count(1)
        u = s + t
        y.append(u)
print(int(max(y)))

n=int(input())
s=input().split()

M=[[0]*n for _ in range(n)]

num=0
for i in range(n):
    if s[i]=='0':
        M[i][i]=1
    else:
        num+=1
Max=0

for j in range(n-1,-1,-1):
    for i in range(i-1,-1,-1):
        if s[i]=='1':
            M[i][j]=M[i+1][j]-1
        else:
            M[i][j]=M[i+1][j]+1
        Max=max(M[i][j],Max)

print(num+Max)

n = int(input())
a = input()
A = list(map(int,list(a.split())))
for i in range(n):
    if A[i] == 0:
        A[i] = -1
table = [0]*(n)
table[0] = A[0]
for  i in range(1,n):
    table[i] = min(A[i],A[i]+table[i-1])
c = 0
m = min(table)
i = 0
while(i<n):
    if table[i]>0:
        c = c+1
        i = i+1
    elif table[i] == m:
        j = i+1
        while(j<n):
            if A[j] == 1:
                c = c+1
            j = j+1
        break
    else:
        i = i+1
print(c-m)

n = int(raw_input())
a = map(int,raw_input().split())
dp = [0]*len(a)
maxs = -1
for i in range(0,len(a)):
	if a[i]==1:
		if i==0:
			dp[i]=1
		elif i == len(a)-1:
			maxs = max(maxs,dp[i-1]+1)
		elif a[i-1]==1:
			dp[i]+=dp[i-1]+1
		elif a[i-1]==0 and (a[i+1]==0 or i==len(a)-1):
			maxs = max(maxs,dp[i-1]+1)
			dp[i] = 1
		elif a[i-1]==0 and a[i+1]==1:
			dp[i]+=dp[i-1]+1
	else:
		if i == 0:
			dp[i]=1
		elif i == len(a)-1:
			maxs = max(maxs,dp[i-1]+1)
		elif a[i-1]==1:
			dp[i]+=dp[i-1]+1
		elif a[i-1]==0:
			dp[i]+=dp[i-1]+1

#print dp
print maxs

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

ll=[]
l1=[]
we=0
cnt=0
for i in range(n):
  if l[i]==0:
    cnt+=1
  ll.append(cnt-((i+1)-cnt))
  if l[i]==1:
    we+=1

#print(ll)
print((max(ll)-min(ll))+we)

n = int(input())
s = list(map(int, input().split(' ')))

maxs, maxed = 0, 0
for kk, vv in enumerate(s):
	cmaxs, i, j, eds = 0, 0, 0, 0
	for x in range(kk, len(s)):
		if s[x] == 0:
			cmaxs = cmaxs + 1
			if cmaxs > maxs:
				maxs = cmaxs
				j = x
		else:
			eds = eds + 1
			if eds > maxed:
				maxed = eds
			cmaxs = cmaxs - 1

print(maxs + maxed)

def solver():
    n = input()
    num = map(int, raw_input().split())

    one = 0
    maxim = 0
    if not (0 in num):
        print n
        return
    for i in range(0,n):
        if i != 0:
            if num[i-1] == 1:
                one += 1
        temp_one = 0

        for j in range(i+1,n):
            if num[j] == 0:
                temp_one += 1
            else:
                temp_one -= 1
            x = num[j:].count(1)
            maxim = max(maxim, one+1+temp_one+x)
            #print maxim
    print maxim

if __name__ == "__main__":
    solver()

m = int(raw_input())
z = map(int, raw_input().split())
z.append(1)
count=0
c={}
for i in range(m+1):
    if z[i]==0:
        count+=1
    else:
        c.update({count:i-count})
        count=0
if c[max(c)]!=0:
    if c[max(c)]+max(c)<m:
        print max(c)+2
    else:
        print max(c)+1
else:
    if c[max(c)]+max(c)<m:
        print max(c)+1
    else:
        print max(c)+1

import os,sys

n = int(raw_input())

arr = raw_input().split()
arr = [int(x) for x in arr]

#def count(arr):
#   return arr.count(1)

maxCount = 0
for i in range(len(arr)-1):
     temp = arr[:]
     for j in range(i,len(temp)-1):
        if temp[j] == 1 and temp[j+1] == 0:
            temp[j+1] = 1
        elif temp[j+1] == 1:
            if temp.count(1) > maxCount:
                maxCount = temp.count(1)
                break

print maxCount

n = int(input())
sp = list(map(int, input().split()))
if 0 in sp:
    d = 0
    d1 = 0
    for el in sp:
        print(el)
        if el == 0: d1 += 1
        else:
            if d1>d: d=d1;d1=0
        if d1>d: d=d1;d1=0
    print(sum(sp)+d)
else:
    print(len(sp)-1)

q=input()
n=input()
l=list(n)
m=len(l)
d=[]
a=0
x=0
while l[a]==l[x]:
    x+=1
    if x<m:
        if l[a] != l[x]:
            d.append(str(x-a))
            a = x
    else:
        d.append(str(x-a))
        break
c=[]
e=[0]
for i in range(len(d)):
    if l[0]=='1':
        if (i+1)%2==0:
            c.append(int(d[i]))
        else:
            e.append(e[-1]+int(d[i]))
    if l[0]=='0':
        if (i+1)%2==0:
            e.append(e[-1]+int(d[i]))
        else:
            c.append(int(d[i]))
g=e[-1]
del(e[0])
b=[0]
for i in c:
        b.append(b[-1]+i)
del(b[0])
if l[-1]=='1':
    del(e[-1])
else:
    pass
del(b[0])
f=[]
for i in range(len(b)):
    f.append(b[i]-e[i])
c.extend(f)
h=max(c)
k=g+h
print(k)

n = map(int, input().split())
arr = list(map(int, input().split()))
cur_sum, res, start, end = 0, 0, 0, 0
if n == 1:
    print(1)
for i in range(len(arr)):
    if cur_sum < 1:
        if not arr[i]:
            cur_sum += 1
            start = i
        else:
            start = i+1
    else:
        if arr[i]:
            if i == len(arr)-1:
                end = i-1
                break
            cur_sum -= 1
            end = i-1
            break
        else:
            cur_sum += 1
        if cur_sum > 0:
            end = i
            res = i-start+1
print(sum(arr[:start]) + sum(arr[end+1:]) + end-start+1-sum(arr[start:end+1]))

n=int(input())
arr=list(map(int,input().split()))
if n==1:
    if arr[0]==1:
        print(0)
    else:
        print(1)
else:
    res=0
    for i in range(n):
        for j in range(i):
            temp=sum(arr[j:i+1])
            temp1=(i-j+1)-temp
            if temp>res:
                res=temp
    print(res+sum(arr))

n=int(input())
s=[int(i) for i in input().split()]
li=list()
if n==1:
    print(1)
else:
    r=1
    for i in range(2,len(s)+1):
        if int(s[i-1])==int(s[i-2]):
            r=r+1
        else:
            li.append(r)
            r=1
print(max(li))

n = int(input())
nums = list(map(int, input().split()))
partial_sum = [None] * (n + 1)
partial_sum[0] = 0
for i in range(1, n + 1):
    partial_sum[i] = partial_sum[i - 1] + nums[i - 1]
max_sum = 0
max_sum_first = partial_sum[-1]
for i in range(n):
    for j in range(i + 1, n + 1):
        s = partial_sum[j] - partial_sum[i]
        if (j - i - s) + max_sum_first > max_sum:
            max_sum = (j - i - s - s) + max_sum_first
print(max_sum)

n=int(input())
A=list(map(int,raw_input().split()))
if(A.count(1)==n):
    print n-1
    exit()
A=A+[1]
maximo=0
co=0
unos=0
for k in range(n+1):
    if(A[k]==0):
        co+=1
    else:
        if(maximo<co):
            maximo=co
        co=0
        unos+=1
print maximo+unos-1

n=int(input ())
a=list(map(int,input().split()))
d={2:0}
for i in range (len(a)):
    if(a[i]==1):
        d[a[i]]=d.get(a[i],0)+1
b=[0]
i=0
while(i<len(a)):
    if(a[i]==0):
        c=0
        for j in range (i,len(a)):
            if(a[j]==1):
                break
            else:
                c=c+1
        b.append(c)
        i=i+c
    else:
        i=i+1
p=list(d.values())
if(p[len(p)-1]==len(a)):
    print (p[len(p)-1]-1)
else:
    print (p[len(p)-1]+max(b))

import sys

def flipping_game(array):
    start = -1
    end = -1
    best_start = -1
    best_end = -1
    best_win = 0
    current_win = 0
    flips = 0
    for i in range(len(array)):
        if array[i] == '0':
            if start == -1 or flips < 0:
                # new window
                start = i
                end = i
                current_win = 1
                flips = 1
            else:
                end = i
                flips +=1
                current_win +=1
            if current_win > best_win:
                best_start = start
                best_end = end
                best_win = current_win
        else:
            flips -= 1

    count = 0
    index = 0

    if start == -1:
        count = len(array) - 1
    else:
        while index < len(array):
            if index == best_start:
                count += best_win
                index = best_end + 1
            else:
                if array[index] == '1':
                    count += 1
            index += 1

    print count

if __name__ == "__main__":
    num = raw_input()
    str = raw_input()
    str_array = str.split(' ')
    sys.exit(flipping_game(str_array))

'''Author- Akshit Monga'''
n=int(input())
arr=[int(x) for x in input().split()]
val=arr.count(1)
ans=arr.count(1)
for i in range(0,n):
  for j in range(i,n):
    ans=max(ans,val+arr[i:j+1].count(0)-arr[i:j+1].count(1))
print(ans)

n=int(input())
l=list(map(int,input().split()))
a=[]
b=[]
x=0
y=0
for i in l:
    if i==1:
        x+=1
    else:
        y+=1
    a.append(x)
    b.append(y)
h=0
start=0
end=0
for i in range(1,n-1):
    for j in range(i,n):
        d=b[j]-b[i-1]
        if(d>h and d>a[j]-a[i-1]):
            h=d
            p=a[j]-a[i-1]
            start=i
            end=j
for i in range(start,end+1):
    l[i]=(1-l[i])
if(start==1 and l[0]==0):
    l[0]=1
print(sum(l))

n = int(input())
a = [int(i) for i in input().split()][:n]
print(max(sum(a)-3*sum(a[i:j])+j-i for i in range(n) for j in range(i+1,n+1)))

n=int(raw_input())
str=raw_input()
t=[]
initial=0
sum=0
for i in range(0, n):
    t.append(int(str.split(" ")[i]))
for i in range(0,n):
    sum=sum+t[i]
if sum==n:
    print 0
elif sum==0:
    print 1
else:

    for i in range(0, n - 1):
        for j in range(i + 1, n+1):
            t1 = []
            for k in range(i, j):
                t1.append(t[k])
            sum = 0
            for k in range(0, len(t1)):
                if t1[k] == 0:
                    sum += 1
                elif t1[k] == 1:
                    sum -= 1
            if sum > initial:
                initial = sum
                imax = i
                jmax = j
    for i in range(imax, jmax):
        t[i] = 1 - t[i]
    total = 0
    for i in range(0, n):
        total = total + t[i]
    print total

"""
sum0=[]
sum0.append(1)
j=0
for i in range(0,n-1):
    if t[i]==t[i+1]:
        sum[j]+=1
    else:
        j+=1
        sum.append(1)
print sum
"""

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 16:47:18 2018

@author: jinbin
"""

n=int(input());s=[int(i) for i in input().split()];a=m=sum(s)
if 0 in s:
    for i in range(s.index(0),n):
        if s[i]:
            if not(s[i-1]):
                m=max(a,m)
            a-=1
        else:
            a+=1
print(m)

n = int(input())
nums = [int(x) for x in input().split()]
count = float('-inf')

for i in range(n):
    for j in range(n):
        count = max(count, nums[i:j + 1].count(0) - nums[i:j + 1].count(1) + nums.count(1))

print(count)

n = int(input())
arr = list(map(int,input().split()))
filtered_arr =[]
for i in range(n):
    if arr[i] == 0:
        filtered_arr.append(1)
    else:
        filtered_arr.append(-1)

# print(filtered_arr)

max_so_far = max_ending = start = end = 0
for i in range(n):
    max_ending += filtered_arr[i]
    if max_ending < 0:
        max_ending = 0
        start = i
    elif max_so_far < max_ending:
        max_so_far = max_ending
        end = i

count = 0;
for i in range(n):
        if i > start and i <= end:
            continue
        else:
            if arr[i] == 1:
                count+=1

if max_so_far > 0:
    print(max_so_far + count)
else:
    print(n-1)

def kadane(a):
	currMax = globalMax = a[0]
	for i in range(1, len(a)):
		currMax = max(a[i], currMax+a[i])
		globalMax = max(currMax, globalMax)
	return globalMax
n = int(input().strip())
arr = list(map(int, input().strip().split()))
s = sum(arr)
if s == n:
	print(s-1)
else:
	b = [-1 if i else 1 for i in arr]
	print(s+kadane(arr))

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

cnt = 1
c = 1
o = 0
z = 0

l = []

for i in range(n):
    if a[i] == 0:
        for j in range(i+1,n):
            if a[j] == 0:
                cnt +=1
            elif a[j] == 1:
                cnt-=1
            c = max(c,cnt)
        l.append(c)
    else:
        o+=1
if z>0 :
    print(o + max(l))
else:
    print(n)

n = int(input())
l =[int(i) for i in input().split()]
ini_zeros = 0
ini_ones = 0
refer =[]
result = []
a = 0
c = 0
b =0
reverse = []
if sum(l) ==len(l):
    print(len(l)-1)
else:
    for i in range(len(l)):
        if l[i] == 0:
            ini_zeros+=1
            if i != 0 and l[i-1]==1:
                refer.append([ini_ones])
                ini_ones = 0
            if i == len(l)-1:
                refer.append([0,ini_zeros])
        else:
            ini_ones+=1
            if i != 0 and l[i-1] ==0:
                refer.append([0,ini_zeros])
                ini_zeros =0
                if i == len(l) - 1:
                    refer.append([ini_ones])
    print(refer)
    for i in range(len(refer)):
        if refer[i][0] == 0:
            a +=refer[i][-1]
            result.append(a)
        else:
            a -= refer[i][-1]
            result.append(a)
    for i in range(1,len(refer)+1):
        if refer[-i][0] == 0:
            b +=refer[-i][-1]
            reverse.append(b)
        else:
            b -= refer[-i][-1]
            reverse.append(b)
    result.sort()
    reverse.sort()
    print(result)
    print(reverse)
    c = sum(l)+max(result[-1],reverse[-1])
    print(c)

n=int(input())
x=input().split()
y=[0for i in range(n)]
S,s,m=0,0,0
if n==1:
    print(1-int(x[0]))
else:
 for i in range(n):
    x[i]=int(x[i])
    S+=x[i]
 for i in range(n):
    for j in range(i,n):
        t=0
        for k in range(i,j+1):
            t+=x[k]
        s=j-i+1-2*t
        if m<s:
            m=s
 print(m+S)

n=int(input())
s=[int(x)for x in input().split()]
max=0
for i in range(n):
    for j in range(i,n):
        temp=s[i:j].count(0)-s[i:j].count(1)
        if temp>max:
            max=temp
print(max+2)

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

dp = [[0,0,0] for i in range(n+1)]

for i in range(1,n+1):
    _one = 1 if _input[i-1] == 1 else 0
    dp[i][0] = dp[i-1][0] + _one
    dp[i][2] = max(dp[i-1]) + _one
    _one = 1 if _input[i-1] == 0 else 0
    dp[i][1] = max((dp[i-1][0],dp[i-1][1])) + _one

print(max(dp[n]))

n=int(input())
A=''.join(input().split())
c1=A.count('1')
A=A.split('1')
A1=[]
for val in A:
    A1.append(len(val))
A1=max(A1)
print(A1+c1)

# target Expert

# Author : raj1307 - Raj Singh
# Date   : 19.07.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n=ii()
    l=li()

    dp=[0]*n

    if l.count(1)==n:
        print(n-1)
        exit()

    dp[0]=1
    for i in range(1,n):
        c=0
        if l[i]==1:
            c=1

        dp[i]+=max(dp[i-1],dp[i-1]+1-l[i],dp[i-1])

    if dp[n-1]!=n:
        dp[n-1]+=l[-1]

    #print(dp)

    print(dp[n-1])

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()

I = lambda :map(int , raw_input().split())
n = input()
a = I()
b = []
answer = cnt = 1
for i in xrange(1 , n):
    if a[i] != a[i - 1]:
        b.append(cnt)
        cnt = 1
    else:
        cnt += 1
b.append(cnt)
print b[0] - 1 * a[0] if len(b) == 1 else (sum(b) if len(b) == 2 else max(b[i] + b[i + 1] + b[i + 2] for i in range(len(b) - 2)))

input()
b = map(int,raw_input().split())
switcher = 0
counter = 0
min = 0
indexstore = 0
index = 1
tester = 0
totalcount = 0
for item in b:
    if counter >=0:
        switcher = 0
        counter = 0
    if item ==0:
        if switcher ==0:
            firstindex = index
        counter -=1
        switcher = 1
    if item ==1 and switcher ==1:
        counter +=1
    if min>counter:
        min = counter
        indexstore = index
        tempindex = firstindex
    index +=1
print tempindex
print indexstore
for i in range(0,tempindex-1):
    if b[i] ==1:
        totalcount += 1
for i in range(tempindex-1,indexstore):
    if b[i] ==0:
        totalcount +=1
for i in range(indexstore,len(b)):
    if b[i] ==1:
        totalcount +=1
print totalcount

if __name__=='__main__':
    N = int(raw_input())
    inp = raw_input()
    arr = inp.split()
    ind = 0
    ans = 0
    con = 0
    flag = False
    for i in arr:
        if i=='0':
            flag = True
            ind+=1
        else:
            ans+=1
            con = max(con,ind)
            ind=0
    print ans+con

input()
a = input().split(" ") + ["1"]
m, p, c = 0, -1, 0

for i in range(0, len(a)):
    if a[i] == '1':
        c += 1
        m = max(m, i - p - 1)
        p = i

m = m + c - 1

if c == len(a):
    print(m - 1)
else:
    print(m)

n = int(input())
a = [int(x) for x in input().split()]
b = sum(a)
if b == n:
	print(n)
else:
	for i in range(n):
		for j in range(i + 1, n):
			b = max(b, j - i - sum(a[i:j]) + sum(a[:i]) + sum(a[j:]))
	print(b)

n = int(input())
s = list(map(str,input().split()))
ans = 0
zero = 0
MAX_ZERO = -float('inf')
for i in range(n):
    if s[i] == '1':
        ans+=1
        if zero > MAX_ZERO:
            MAX_ZERO = zero
            zero = 0
    else:
        zero+=1
zero = max(zero, MAX_ZERO)
print(zero+ans)

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

print max([(a[i:j].count(0)-sum(a[i:j])) for i in xrange(n) for j in xrange(1, n+1)])+sum(a)

from sys import stdin

def inp():
    return stdin.readline().strip()

n = int(inp())
ones = 0
longest = 0
streak = 0
begin = 0
zero = False
a = [int(x) for x in inp().split()]
for i in range(n):
    if a[i] == 1:
        if not zero:
            begin+=1
        else:
            ones += 1
        if streak > 0:
            longest = max(longest, streak)
            streak = 0
    elif a[i] == 0:
        streak+=1
        zero = True
longest = max(longest, streak)
if not zero:
    print(0)
else:
    lens = n - begin
    ans2 = begin + (lens-ones)
    print(max(ans2, longest+begin+ones))

n = int(input())
a = input().split()

maxSoFar = max(a.count('1'),a.count('0'))

for i in range(n):
    for j in range(i+1):
        maxSoFar = max(maxSoFar,(a[:j]+a[i+1:]).count('1')+a[j:i+1].count('0'))
print(maxSoFar)

import re
regexp = re.compile('[0]+')

n = input()
_input = list(map(int,input().split()))
count_1 = 0
for x in _input:
    if x == 1:
        count_1 += 1
str = ''.join(map(str,_input))
tmp = regexp.findall(str)
_max = 0
if tmp:
    _max = max([len(x) for x in tmp])
print(_max + count_1)

n=input()
line=[int(i) for i in input().split()]
if len(line)>1:
    s=0
    for i in range(0,len(line)-1):
        for j in range(i+1,len(line)+1):
            for k in range(i-1,j):
                line[k]=1-line[k]
                if sum(line)>s:
                    s=sum(line)
else:
    if line[0]==1:
        s=0
    else:
        s=1
print(s)

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

m = 0
c = 0
x = 0
for i in range(n):
    if l[i] == 1:
        x += 1
        m = max(m,c)
        c = 0
    else:
        c += 1
m = max(m,c)
if m == 0:
    m = -1
print(m+x)

x = int(input())
li = list(map(int, input().split()))
try:
	a = li.index(0)
except:
	print(x)
	exit()
ans,  cnt, b = 0,0, a
for i in li[a:]:
	cnt += -1 if i else 1
	b +=1
	ans = max(ans, cnt + li[a:].count(1))
print(a  + ans)

n = int(input())

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

def flipping(ls,i = 0, j = 0, result = []):
    return  i == len(ls) and str(max(result)) or \
            j == len(ls[i:]) and flipping(ls,i+1,0,result) or \
            flipping(ls,i,j+1,result + \
            [sum(ls[:i] + [0 if n == 1 else 1 for n in ls[i:j+1]] + ls[j+1:])])

print(flipping(ls))

import re
regexp = re.compile('[0]+')

n = input()
_input = list(map(int,input().split()))
count_1 = 0
for x in _input:
    if x == 1:
        count_1 += 1
str = ''.join(map(str,_input))
tmp = regexp.findall(str)
_max = 0
if tmp:
    _max = max([len(x) for x in tmp])
else:
    count_1 -= 1
print(_max + count_1)

def flip(l,a,b):
    for i in range(a,b):
        if l[i] == 1:
            l[i] = 0
        else:
            l[i] = 1

    return l

def solver():
    n = input()
    num = map(int, raw_input().split())
    maxim = 0
    if n == 1:
        if num[0] == 0:
            print 1
        else:
            print 0

        return

    for i in range(0,n):
        for j in range(i,n+1):
            new_b = num[:]
            new_b = flip(new_b,i,j)
            maxim = max(maxim,new_b.count(1))
            #print new_b

    print maxim

if __name__ == "__main__":
    solver()

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

#find the maximum distance between two consecutive ones
if l1 == 1:
    print(0)
elif l1.count(1) == 0:
    print(n)
elif l1.count(1) == 1:
    getidx = l1.index(1)
    print(max(getidx + 1, n - getidx + 1))
else:
    posi = []
    for i in range(n):
        if l1[i] == 1:
            posi.append(i)

    max1 = 0
    prev = 0
    #print(posi)
    for i in posi:
        temp = i - prev
        prev = i
        if temp > max1:
            max1 = temp
    print(max1 + 1)

n = int(input())
lst = [int(x) for x in input().split()]

cur_num = sum(x==1 for x in lst)
def trans(x):
    return -1 if x==1 else 1
sum_lst = [0]
for el in lst:
    sum_lst.append(lst[-1]+trans(el))

#we need all sums from i inclusive to j exclusive, 0<=i<j<n
#sum_lst[j]-sum_lst[i] is the sum i+1 to j inclusive
max_sum = -1
for i in range(n):
    for j in range(i+1,n+1):
        cur = sum_lst[j]-sum_lst[i]
        if cur>max_sum:
            max_sum = cur
print(max_sum+cur_num)

a = int(input())

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

e = t.count(1)

for k in range(a+1):
    for j in range(k+1,a+1):
        p=t[k:j]
        q=t[0:k]
        s=t[j:]
        z= q.count(1)+p.count(0)+s.count(1)

        if z>e:
            e=z

print(e)

import sys

input = sys.stdin.readline()
n = int(input)
input = sys.stdin.readline()
digits = map(int, input.split(' '))

max_sum = -1000
max_i = 0
max_j = 0

for i in range(n):
	for j in range(n):

		temp_sum = 0;

		for k in range(n):

			if k >= i and k <= j:
				temp_sum += 1 - digits[k]
			else:
				temp_sum += digits[k]

			#print "i: %i, j: %i, k: %i, temp_summ: %i" % (i, j, k, temp_sum)

		if temp_sum > max_sum:
			max_sum = temp_sum
			max_i = i
			max_j = j

print "%i" % (max_sum)

n = int(input())
bits = list(map(int, input().split()))
ones = bits.count(1)
Max = ones

for i in range(n):
    for j in range(i, n):
        inv = bits[i:j+1]
        cur = ones-inv.count(1)
        Max = max(Max, cur+inv.count(0))

print(Max)

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

#find the maximum distance between two consecutive ones
if l1 == [1]:
    print(0)
elif l1.count(1) == 0:
    print(n)
elif l1.count(1) == 1:
    getidx = l1.index(1)
    print(max(getidx + 1, n - getidx + 1))
else:
    posi = []
    for i in range(n):
        if l1[i] == 1:
            posi.append(i)

    max1 = 0
    prev = 0
    #print(posi)
    for i in posi:
        temp = i - prev
        prev = i
        if temp > max1:
            max1 = temp
    print(max1 + 1)

read_ints = lambda : map(int, raw_input().split())

def main():
    n = input()
    a = read_ints()
    c = a.count(1)
    ans = c
    for i in range(n):
        for j in xrange(i, n):
            t = c
            for k in xrange(i, j+1):
                if a[k] == 1:
                    t -= 1
                else:
                    t += 1
            if t > ans:
                ans = t
    print ans

if __name__ == '__main__':
    main()

import sys

s = sys.stdin.readline()
n = int(s.split()[0])

s = sys.stdin.readline()
arr = map(int, s.split())

maxSum = 0
curSum = 0

sumOnes = 0
for i in arr:
	sumOnes += i
	if (i & 1):
		if (curSum > maxSum):
			maxSum = curSum
		if (curSum == 0):
			continue
		curSum -= 1
	else: curSum += 1

if maxSum > curSum:
	maxSum += sumOnes
else: maxSum = curSum + sumOnes

print(maxSum)
#1 0 0 1 1 0 0 0 1 0 1 0 0 1 1

n = int(input())
num_lst = [int(i) for i in input().split()]
output = []
if n == num_lst.count(1):
    print(n-1)
else:
    for i in range(n):
        for j in range(n):
            total = 0
            lst1 = num_lst[i:j]
            lst2 = num_lst[:i]
            lst3 = num_lst[j:]
            total += lst1.count(1)+lst2.count(0)+lst3.count(1)
            output.append(total)
    print(max(output))

#credit hyperhyperhypercubelover
x = int(input())
li = list(map(int, input().split()))
ans = 0
for i  in range(1,x):
	li[i]+= li[i-1]
for i in range(x-1):
	for j  in range(i+1,x):
		ans  = max(ans, li[i] + li[x-1]-li[j] + j-i - li[j]+ li[i])
print(ans)

# cook your dish here
n=int(input())
a=list(map(int,input().rstrip().split()))
tillnoq=0
count1=0
count0=0
if n==1 and a[0]==1:
    print(1)
elif n==1 and a[0]==0:
    print(0)
else:
    for i in range (n):
        for j in range (i,n):
            if a[j]==1:
                count1+=1
            else:
                count0+=1
        #print(count0,count1,i,j)
            numzeroabs=count0-count1
            if numzeroabs>tillnoq:
                left=i
                right=j
                tillnoq=numzeroabs
        #print(numzeroabs)
        count0=0
        count1=0
    cntr=0
    for i in range (left):
        if a[i]==1:
            cntr+=1
    for i in range (right,n):
        if a[i]==1:
            cntr+=1

    print(cntr+tillnoq)

n = int(input())

s=input().split()

for i in range(n):
    s[i]=int(s[i])

ans=sum(s)
if(len(s)==1):
    print(1-s[0])
elif(s.count(0)==len(s)):
    print(len(s))
elif(s.count(1)==len(s)):
    print(sum(s)-1)
else:
    r=0
    if(s[0]==0):
       s=[1]+s
       r=1
    L=[0]
    for i in range(1,n):
        if(s[i]!=s[i-1]):
            L.append(i)
    L.append(n)
    m=len(L)
    maxx=0
    for i in range(2,m,2):
        ans=sum(s)-r+L[i]-L[i-1]
        for j in range(i+2,m,2):
            if(ans+L[j]-L[j-1]-(L[j-1]-L[j-2])>ans):
                ans=ans+L[j]-L[j-1]-(L[j-1]-L[j-2])
                continue
            else:
                break
        if(ans>maxx):
            maxx=ans
    print(maxx)