Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $s$ into $t$ using the following operation as few times as possible.

In one operation, he can choose any subsequence of $s$ and rotate it clockwise once.

For example, if $s = 1\textbf{1}101\textbf{00}$, he can choose a subsequence corresponding to indices ($1$-based) $\{2, 6, 7 \}$ and rotate them clockwise. The resulting string would then be $s = 1\textbf{0}101\textbf{10}$.

A string $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the ordering of the remaining characters.

To perform a clockwise rotation on a sequence $c$ of size $k$ is to perform an operation which sets $c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$ simultaneously.

Determine the minimum number of operations Naman has to perform to convert $s$ into $t$ or say that it is impossible. 


-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 10^6)$ — the length of the strings.

The second line contains the binary string $s$ of length $n$.

The third line contains the binary string $t$ of length $n$.


-----Output-----

If it is impossible to convert $s$ to $t$ after any number of operations, print $-1$.

Otherwise, print the minimum number of operations required.


-----Examples-----
Input
6
010000
000001

Output
1
Input
10
1111100000
0000011111

Output
5
Input
8
10101010
01010101

Output
1
Input
10
1111100000
1111100001

Output
-1


-----Note-----

In the first test, Naman can choose the subsequence corresponding to indices $\{2, 6\}$ and rotate it once to convert $s$ into $t$.

In the second test, he can rotate the subsequence corresponding to all indices $5$ times. It can be proved, that it is the minimum required number of operations.

In the last test, it is impossible to convert $s$ into $t$.

Difficulty: HARD
Tags: Sorting

Constructive algorithms

Data structures

Greedy algorithms
Skill types: Sorting

Data structures

Greedy algorithms

Starter code:

Solutions:
import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, s, t):
	if s.count('1') != t.count('1'):
		return -1
	m1 = 0
	m2 = 0
	balance = 0
	for i in range(n):
		if s[i] == '1':
			balance += 1
		if t[i] == '1':
			balance -= 1
		m1 = max(m1, balance)
		m2 = min(m2, balance)
	return m1 - m2

def main():
	n = ri()
	s = rs()
	t = rs()
	wi(solve(n, s, t))
main()


import sys
from fractions import gcd
from math import ceil, sqrt, sin, pi, tan
from collections import defaultdict
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())

def sol():
	pass

def isp(n):
	i = 2
	while i * i <= n:
		if n % i == 0:
			return False
		i += 1
	return True
for _t in range(1):
	n = int(input())
	a = input()
	b = input()
	s = ''
	(e0, e1) = (0, 0)
	(nz, no) = (0, 0)
	for i in range(n):
		if a[i] != b[i]:
			if b[i] == '1':
				no += 1
				if e0 > 0:
					e0 -= 1
				e1 += 1
			else:
				nz += 1
				if e1 > 0:
					e1 -= 1
				e0 += 1
	if nz != no:
		print(-1)
	else:
		print(e0 + e1)


import sys
n = int(input())
s = input()
t = input()
ssum = 0
tsum = 0
for i in range(n):
	ssum += int(s[i])
	tsum += int(t[i])
if ssum != tsum:
	print(-1)
	sys.exit()
nex = [0, 0]
for i in range(n):
	if s[i] == '0' and t[i] == '1':
		if nex[1] > 0:
			nex[1] -= 1
			nex[0] += 1
		else:
			nex[0] += 1
	if s[i] == '1' and t[i] == '0':
		if nex[0] > 0:
			nex[0] -= 1
			nex[1] += 1
		else:
			nex[1] += 1
print(sum(nex))


(n, s, t, p) = (int(input()), input(), input(), [0])
for i in range(n):
	if s[i] != t[i]:
		p.append(p[-1] + (1 if s[i] == '1' else -1))
print(max(p) - min(p) if p[-1] == 0 else -1)


import math as mt
import sys
I = lambda : list(map(int, input().split()))
(n,) = I()
maxint = mt.inf
s = list(input())
t = list(input())
if sorted(s) != sorted(t):
	print(-1)
	sys.exit()

def ma(a, size):
	max_so_far = -maxint - 1
	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
ar = [0] * n

def mi(a, size):
	max_so_far = maxint - 1
	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 abs(max_so_far)
for i in range(n):
	if s[i] == '1' and t[i] == '0':
		ar[i] = 1
	elif s[i] == '0' and t[i] == '1':
		ar[i] = -1
print(max(ma(ar, n), mi(ar, n)))


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	inf = 10 ** 9
	n = II()
	s = SI()
	t = SI()
	if s.count('1') != t.count('1'):
		print(-1)
		exit()
	cnt = 0
	mx = -inf
	mn = inf
	for (c1, c2) in zip(s, t):
		if c1 == '1':
			cnt += 1
		if c2 == '1':
			cnt -= 1
		if cnt > mx:
			mx = cnt
		if cnt < mn:
			mn = cnt
	print(mx - mn)
main()


n = int(input())
todo = [0 for i in range(n)]
a = input()
b = input()
for i in range(n):
	if a[i] == b[i]:
		todo[i] = 0
	elif a[i] == '0' and b[i] == '1':
		todo[i] = 1
	else:
		todo[i] = -1
(maxx1, maxx2) = (0, 0)
(res1, res2) = (0, 0)
for i in range(n):
	if res2 == 0 and todo[i] == 1 and (res1 + todo[i] <= 0) or (todo[i] == -1 and res2 == 0):
		res1 += todo[i]
		maxx1 = max(abs(res1), maxx1)
	else:
		res2 += todo[i]
		maxx2 = max(abs(res2), maxx2)
if res1 != 0 or res2 != 0:
	print(-1)
else:
	print(maxx1 + maxx2)


def help():
	n = int(input())
	s1 = list(input())
	s2 = list(input())
	if s1 == s2:
		print(0)
		return
	if s1.count('1') != s2.count('1'):
		print('-1')
		return
	operate = []
	for i in range(n):
		if s1[i] != s2[i]:
			operate.append(1 if s1[i] == '1' else -1)
	ll = len(operate)
	op1 = [0] * ll
	op1[0] = operate[0]
	for i in range(1, ll):
		op1[i] = operate[i] + op1[i - 1]
	ans = abs(max(op1) - min(op1))
	print(ans)
help()


import collections

def next_char(c):
	return '1' if c == '0' else '0'

def find_subseqs(s):
	subsequences = []
	next_chars = collections.defaultdict(set)
	for s_c in s:
		target_subseq = None
		if next_chars[s_c]:
			target_subseq = next(iter(next_chars[s_c]))
		else:
			target_subseq = len(subsequences)
			subsequences.append([])
		if subsequences[target_subseq]:
			next_chars[s_c].remove(target_subseq)
		next_chars[next_char(s_c)].add(target_subseq)
		subsequences[target_subseq].append(s_c)
	return len(subsequences)

def main():
	input()
	s = input().strip()
	t = input().strip()
	s_t = [(s_c, t_c) for (s_c, t_c) in zip(s, t) if s_c != t_c]
	if not s_t:
		print(0)
		return
	(s, t) = zip(*s_t)
	(s, t) = (''.join(s), ''.join(t))
	if collections.Counter(s) != collections.Counter(t):
		print(-1)
		return
	print(find_subseqs(s))
main()


n = int(input())
s = input()
t = input()
s1 = 0
t1 = 0
if s == t:
	print(0)
else:
	for i in range(n):
		if s[i] == '1':
			s1 += 1
		if t[i] == '1':
			t1 += 1
	if s1 != t1:
		print(-1)
	else:
		stype1 = 0
		stype2 = 0
		for i in range(n):
			if s[i] == '1' and t[i] == '0':
				stype1 += 1
				stype2 = max(0, stype2 - 1)
			elif s[i] == '0' and t[i] == '1':
				stype2 += 1
				stype1 = max(0, stype1 - 1)
		print(stype1 + stype2)


def get(x):
	(cur, mx) = (0, 0)
	for i in range(n):
		cur += x * L[i]
		mx = max(mx, cur)
		if cur < 0:
			cur = 0
	return mx
n = int(input())
s = str(input())
t = str(input())
L = []
for (x, y) in zip(s, t):
	if x == y:
		L.append(0)
	elif x == '1' and y == '0':
		L.append(1)
	else:
		L.append(-1)
if sum(L) != 0:
	print(-1)
elif s == t:
	print(0)
else:
	print(max(get(1), get(-1)))


m = int(input())
s = list(input())
t = list(input())
i = 0
a = c = d = 0
while i < m:
	if s[i] != t[i]:
		if s[i] == '0':
			a += 1
		else:
			a -= 1
		c = min(c, a)
		d = max(d, a)
	i += 1
if a == 0:
	print(d - c)
else:
	print(-1)


n = int(input())
s1 = input()
s2 = input()
mn = 0
mx = 0
c = 0
for i in range(n):
	if s1[i] == '1':
		c += 1
	if s2[i] == '1':
		c -= 1
	mn = min(mn, c)
	mx = max(mx, c)
if c != 0:
	print(-1)
else:
	print(mx - mn)


n = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
	print(-1)
	exit(0)
s1 = 0
s2 = 0
ans1 = 0
ans2 = 0
for i in range(len(s)):
	if s[i] != t[i]:
		if s[i] == '0':
			if s2 > 0:
				s2 -= 1
			else:
				s1 += 1
				ans1 = max(ans1, s1)
		elif s1 > 0:
			s1 -= 1
		else:
			s2 += 1
			ans2 = max(ans2, s2)
print(ans1 + ans2)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 998244353

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k))))
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def solution(s1, s2):
	if s1.count('1') != s2.count('1'):
		return -1
	z_o = 0
	z_e = 0
	o_o = 0
	o_e = 0
	for i in range(len(s1)):
		if s1[i] == '1' and s2[i] == '0':
			if z_o > 0:
				o_e += 1
				z_o -= 1
			elif z_e > 0:
				o_o += 1
				z_e -= 1
			else:
				o_o += 1
		elif s1[i] == '0' and s2[i] == '1':
			if o_o > 0:
				z_e += 1
				o_o -= 1
			elif o_e > 0:
				z_o += 1
				o_e -= 1
			else:
				z_o += 1
	return z_o + z_e + o_o + o_e
	b1 = int(s1, 2)
	b2 = int(s2, 2)
	b = b1 ^ b2
	bs = bi(b)

def main():
	T = 1
	for i in range(T):
		n = ri()
		s1 = f.readline().strip()
		s2 = f.readline().strip()
		x = solution(s1, s2)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


n = int(input())
s = input()
t = input()
arr = []
(ze, on) = (0, 0)
for i in range(n):
	if s[i] != t[i]:
		if int(s[i]):
			on += 1
		else:
			ze += 1
		arr.append(int(s[i]))
if ze != on:
	print(-1)
else:
	on = []
	ze = []
	res = 0
	for i in arr:
		if i == 0:
			if on:
				on.pop()
				ze.append(0)
			else:
				ze.append(0)
				res += 1
		elif ze:
			ze.pop()
			on.append(1)
		else:
			on.append(1)
			res += 1
	print(res)


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
q = int(input())
w = input()
e = input()
r = []
if w.count('1') != e.count('1'):
	print(-1)
	exit()
if w.count('1') == q or w.count('1') == 0:
	print(0)
	exit()
for i in range(q):
	if w[i] != e[i]:
		r.append(e[i])
k = 0
l = []
for i in r:
	if i == '1':
		k += 1
	else:
		k -= 1
	l.append(k)
print(max(l) + abs(min(l)))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
import datetime
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	starttime = datetime.datetime.now()
	n = int(input())
	s = input()
	t = input()
	su = 0
	on = 0
	ze = 0
	v = []
	for i in range(1, n + 1):
		if s[i - 1] != t[i - 1]:
			if s[i - 1] == '1':
				v.append(0)
				ze += 1
			else:
				v.append(1)
				on += 1
	if on - ze != 0:
		print(-1)
	else:
		ua = 0
		ub = 0
		mxa = 0
		mxb = 0
		for i in range(len(v)):
			if not v[i]:
				if ub == 0:
					ua += 1
				else:
					ub -= 1
			elif ua == 0:
				ub += 1
			else:
				ua -= 1
			mxa = max(mxa, ua)
			mxb = max(mxb, ub)
		print(mxa + mxb)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
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):
	(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')
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

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

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
t = 1
for _ in range(t):
	m = int(input())
	s = input()
	t = input()
	i = 0
	a = c = d = 0
	while i < m:
		if s[i] != t[i]:
			if s[i] == '0':
				a += 1
			else:
				a -= 1
			c = min(c, a)
			d = max(d, a)
		i += 1
	if a == 0:
		print(d - c)
	else:
		print(-1)


import sys
input = sys.stdin.readline

def main():
	_ = int(input())
	a = list(input().rstrip())
	a = list(map(int, a))
	b = list(input().rstrip())
	b = list(map(int, b))
	if sorted(a) != sorted(b):
		print('-1')
		return
	c = [0, 0]
	ans = 0
	for (x, y) in zip(a, b):
		if x == y:
			continue
		if c[x ^ 1] > 0:
			c[x ^ 1] -= 1
		else:
			ans += 1
		c[x] += 1
	print(ans)
main()


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
	exit()
x = [s[i] for i in range(n) if s[i] != t[i]]
(v1, v2, w1, w2) = (0, 0, 0, 0)
for i in x:
	if i == '0':
		if w2 == 0:
			if v1 == v2:
				v1 += 1
			v2 += 1
		else:
			w2 -= 1
	elif v2 == 0:
		if w1 == w2:
			w1 += 1
		w2 += 1
	else:
		v2 -= 1
print(v1 + w1)


n = int(input())
a = list(map(int, input()))
b = list(map(int, input()))
c = []
if sum(a) != sum(b):
	print(-1)
	exit()
for i in range(n):
	if a[i] != b[i]:
		c.append(a[i])
open1 = 0
open0 = 0
flag1 = False
flag0 = False
ans = 0
oooopen1 = 0
oooopen0 = 0
for i in c:
	if i == 0:
		if open1 > 0:
			open1 -= 1
		else:
			open0 += 1
			flag0 = True
	elif open0 > 0:
		open0 -= 1
	else:
		open1 += 1
		flag1 = True
	oooopen1 = max(oooopen1, open1)
	oooopen0 = max(oooopen0, open0)
	ans = max(ans, oooopen1 + oooopen0)
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
s = input()
t = input()
fault1 = 0
fault2 = 0
li = [0] * n
for i in range(n):
	if s[i] != t[i]:
		if s[i] == '1':
			fault1 += 1
			li[i] += 1
		else:
			fault2 += 1
			li[i] -= 1
if fault1 != fault2:
	print(-1)
else:
	for i in range(1, n):
		li[i] += li[i - 1]
	print(max(li) - min(li))


n = int(input())
s = list(map(str, input()))
t = list(map(str, input()))
(a, b) = (0, 0)
for i in s:
	if i == '1':
		a += 1
for i in t:
	if i == '1':
		b += 1
if a != b:
	print(-1)
elif s == t:
	print(0)
else:
	(ones, zeros) = (0, 0)
	for i in range(n):
		if s[i] == '1' and t[i] == '0':
			if zeros:
				zeros -= 1
			ones += 1
		elif s[i] == '0' and t[i] == '1':
			if ones:
				ones -= 1
			zeros += 1
	print(ones + zeros)


(n, s, t) = (int(input()), input(), input())
ar = [0 if s[i] == t[i] else 2 * (s[i] == '1') - 1 for i in range(n)]

def f(x):
	(c, s) = (0, 0)
	for e in ar:
		c = max(c + e * x, e * x)
		s = max(s, c)
	return s
print(max(f(1), f(-1)) if s.count('1') == t.count('1') else -1)


import sys
input = sys.stdin.readline
n = int(input())
s = list(input().rstrip())
t = list(input().rstrip())
if s.count('1') != t.count('1'):
	print(-1)
	exit()
s11 = 0
s10 = 0
s01 = 0
s00 = 0
for i in range(n):
	if s[i] != t[i]:
		if s[i] == '1':
			if s00:
				s00 -= 1
				s01 += 1
			elif s10:
				s10 -= 1
				s11 += 1
			else:
				s11 += 1
		elif s11:
			s11 -= 1
			s10 += 1
		elif s01:
			s01 -= 1
			s00 += 1
		else:
			s00 += 1
print(s01 + s10)


n = int(input())
a = list(map(str, input().strip()))
b = list(map(str, input().strip()))
x = []
import sys
input = sys.stdin.readline
for i in range(n):
	if a[i] != b[i]:
		x += [a[i]]
zero = 0
one = 0
co = 0
for i in x:
	if i == '0':
		co += 1
		if one != 0:
			one -= 1
			zero += 1
		else:
			zero += 1
	else:
		co -= 1
		if zero != 0:
			zero -= 1
			one += 1
		else:
			one += 1
if co == 0:
	print(zero + one)
else:
	print(-1)


rr = lambda : input().strip()
(n, s, t) = (int(rr()), rr(), rr())
curr = 0
currs = []
for i in range(n):
	if s[i] == '1':
		curr += 1
	if t[i] == '1':
		curr -= 1
	currs.append(curr)
if curr != 0:
	print(-1)
else:
	print(max(currs) - min(currs))


n = int(input())
s = input()
t = input()
moves = []
s1_z = 0
s2_z = 0

def check(num):
	ret = 0
	mx = 0
	for z in moves:
		ret += num * z
		mx = max(mx, ret)
		if ret < 0:
			ret = 0
	return mx
for i in range(n):
	if s[i] == '0':
		s1_z += 1
	if t[i] == '0':
		s2_z += 1
	if s[i] != t[i]:
		if s[i] == '1':
			moves.append(-1)
		else:
			moves.append(1)
if s1_z != s2_z:
	print(-1)
else:
	print(max(check(1), check(-1)))


from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *

@lru_cache(None)
def fact(x):
	if x < 2:
		return 1
	return fact(x - 1) * x

@lru_cache(None)
def per(i, j):
	return fact(i) // fact(i - j)

@lru_cache(None)
def com(i, j):
	return per(i, j) // fact(j)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

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

def power2(n):
	while not n & 1:
		n >>= 1
	return n == 1
n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
	exit()
(one, zero) = (0, 0)
ans = 0
for i in range(n):
	if s[i] != t[i]:
		if s[i] == '1':
			if zero:
				zero -= 1
			one += 1
			ans = max(one, ans)
		else:
			if one:
				one -= 1
			zero += 1
			ans = max(zero, ans)
print(ans)


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
	exit(0)
p = []
ans = [0, 0]
for i in range(n):
	if s[i] != t[i]:
		if p and s[i] != p[-1]:
			p.pop(-1)
		else:
			p.append(s[i])
			w = int(s[i])
			ans[w] = max(ans[w], len(p))
print(sum(ans))


import math
from collections import deque
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 2
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	result.append(n)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < abs(max_ending_here):
			max_so_far = max_ending_here
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	n = int(input())
	s1 = input()
	s2 = input()
	l1 = []
	c1 = 0
	c2 = 0
	for j in range(0, n):
		if s1[j] != s2[j]:
			l1.append(s1[j])
		if s1[j] == '1':
			c1 += 1
		if s2[j] == '1':
			c2 += 1
	if c1 != c2:
		print(-1)
	elif len(l1) == 0:
		print(0)
	else:
		c1 = 0
		c2 = 0
		for j in range(0, len(l1)):
			if l1[j] == '0':
				if c2 != 0:
					c2 -= 1
					c1 += 1
				else:
					c1 += 1
			elif c1 != 0:
				c1 -= 1
				c2 += 1
			else:
				c2 += 1
		print(c1 + c2)
t = 1
for i in range(0, t):
	main()


n = int(input())
s = input()
t = input()
ss = []
tt = []
s0 = 0
s1 = 0
t0 = 0
t1 = 0
for i in range(n):
	if s[i] == '0':
		s0 += 1
	elif s[i] == '1':
		s1 += 1
	if t[i] == '0':
		t0 += 1
	elif t[i] == '1':
		t1 += 1
	if s[i] == t[i]:
		continue
	else:
		ss.append(s[i])
		tt.append(t[i])
if s0 != t0 or s1 != t1:
	print(-1)
else:
	dip = 0
	rise = 0
	pit = 0
	for i in ss:
		if i == '0':
			pit -= 1
			dip = min(dip, pit)
		else:
			pit += 1
			rise = max(rise, pit)
	print(rise - dip)


from math import sqrt
it = lambda : list(map(int, input().strip().split()))

def solve():
	input()
	s = input().strip()
	t = input().strip()
	z = 0
	o = 0
	l = []
	for (ch1, ch2) in zip(s, t):
		if ch1 != ch2:
			if ch1 == '0':
				l.append(1)
				z += 1
			else:
				assert ch1 == '1'
				l.append(-1)
				o += 1
	if z != o:
		return -1
	a1 = 0
	c1 = 0
	c2 = 0
	for x in l:
		c1 = max(x, c1 + x)
		c2 = max(-x, c2 - x)
		a1 = max(a1, c1, c2)
	return a1
print(solve())


n = int(input())
a = list(map(int, list(input())))
b = list(map(int, list(input())))
if sum(a) != sum(b):
	print(-1)
	exit()
if a == b:
	print(0)
	exit()
u = []
for i in range(n):
	if a[i] == b[i]:
		continue
	elif a[i] == 1:
		u.append(1)
	else:
		u.append(-1)
k = 0
d = []
for i in range(len(u)):
	k += u[i]
	d.append(k)
print(max(d) + abs(min(d)))


import sys
input = sys.stdin.readline
n = int(input())
s = list(input().rstrip())
t = list(input().rstrip())
if s.count('1') != t.count('1'):
	print(-1)
	exit()
ns = []
for (si, ti) in zip(s, t):
	if si != ti:
		ns.append(si)
ns = ns + ns
d = 0
ans = 0
for item in ns:
	if item == '1':
		d += 1
	else:
		d -= 1
		if d < 0:
			d = 0
	ans = max(ans, d)
print(ans)


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
else:
	a = []
	for i in range(n):
		if s[i] == t[i]:
			a.append(0)
		elif s[i] == '1':
			a.append(1)
		else:
			a.append(-1)
	mx = -1
	mn = 10 ** 9
	sm = 0
	tmax = -1
	tmin = 10 ** 9
	for i in range(n):
		sm += a[i]
		mx = max(mx, sm - tmin)
		mn = min(mn, sm - tmax)
		tmin = min(tmin, sm)
		tmax = max(tmax, sm)
	print(max(mx, abs(mn)))


import sys
input = sys.stdin.readline
inputr = lambda : input().rstrip('\n')
n = int(input())
S = inputr()
T = inputr()
if S.count('1') != T.count('1'):
	print(-1)
	sys.exit(0)
needz = []
needo = []
for i in range(n):
	if S[i] == T[i]:
		continue
	if S[i] == '1':
		if needo:
			needz.append(needo.pop())
		else:
			needz.append(None)
	elif needz:
		needo.append(needz.pop())
	else:
		needo.append(None)
print(len(needz) + len(needo))


n = int(input())
a = str(input())
b = str(input())
v = [0] * n
(cur, curr) = (0, 0)
(x, mx) = (0, 0)
for i in range(n):
	if a[i] != b[i]:
		if a[i] == '1':
			v[i] -= 1
		else:
			v[i] = 1
if sum(v) != 0:
	print(-1)
else:
	for i in range(n):
		cur += 1 * v[i]
		x = max(x, cur)
		cur = max(0, cur)
	for i in range(n):
		curr += -1 * v[i]
		mx = max(mx, curr)
		curr = max(0, curr)
	print(max(x, mx))


n = int(input())
s = input()
t = input()
(k, f, mx, mn) = (0, 0, 0, 0)
for i in range(n):
	if s[i] == '1':
		f += 1
	if t[i] == '1':
		f -= 1
	if s[i] == '0' and t[i] == '1':
		k += 1
	elif s[i] == '1' and t[i] == '0':
		k -= 1
	mx = max(mx, k)
	mn = min(mn, k)
if f != 0:
	print(-1)
else:
	print(mx - mn)


n = int(input())
s = input()
t = input()
res = 0
(counts0, counts1, countt0, countt1) = (0, 0, 0, 0)
(start0, start1) = (0, 0)
for i in range(n):
	if s[i] == t[i]:
		continue
	elif s[i] == '0':
		counts0 += 1
		countt1 += 1
		if start1 == 0:
			res += 1
			start0 += 1
		else:
			start1 -= 1
			start0 += 1
	else:
		counts1 += 1
		countt0 += 1
		if start0 == 0:
			res += 1
			start1 += 1
		else:
			start0 -= 1
			start1 += 1
if counts0 != countt0 or counts1 != countt1:
	print(-1)
else:
	print(res)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
s = li3()
t = li3()
if Counter(s) != Counter(t):
	print(-1)
	exit()
index = []
for i in range(n):
	if s[i] != t[i]:
		index.append([s[i], i])
ans = 0
zeros = 0
ones = 0
for i in range(len(index) - 1, -1, -1):
	if index[i][0]:
		if ones:
			zeros += 1
			ones -= 1
		else:
			zeros += 1
	elif zeros:
		zeros -= 1
		ones += 1
	else:
		ones += 1
	ans = max(ans, zeros + ones)
print(ans)


def some_random_function():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function5():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
import os, sys
from io import BytesIO, IOBase

class SortedList:

	def __init__(self, iterable=None, _load=200):
		if iterable is None:
			iterable = []
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def main():
	n = int(input())
	s = input().strip()
	t = input().strip()
	arr = [SortedList(), SortedList()]
	for (ind, i) in enumerate(s):
		if i != t[ind]:
			if i == '0':
				arr[0].add(ind)
			else:
				arr[1].add(ind)
	ans = 0
	while len(arr[0]) and len(arr[1]):
		(k, prev) = (arr[0][0] < arr[1][0], -1)
		while 1:
			ind = arr[k ^ 1].bisect_left(prev)
			if ind == len(arr[k ^ 1]):
				break
			ind1 = arr[k].bisect_left(arr[k ^ 1][ind])
			if ind1 != len(arr[k]):
				prev = arr[k][ind1]
				arr[k ^ 1].pop(ind)
				arr[k].pop(ind1)
			else:
				break
		ans += 1
	if len(arr[0]) or len(arr[1]):
		print(-1)
	else:
		print(ans)
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def some_random_function1():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function2():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function3():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function4():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function6():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function7():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function8():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
main()


import sys
input = sys.stdin.readline
n = int(input())
S = input().strip() * 2
T = input().strip() * 2
if S.count('1') != T.count('1'):
	print(-1)
	sys.exit()
count = 0
MAX = 0
for i in range(2 * n):
	if S[i] == T[i]:
		continue
	else:
		if S[i] == '1':
			count += 1
		else:
			count = max(0, count - 1)
		MAX = max(MAX, count)
print(MAX)


def answer(n, s, t):
	if s == t:
		return 0
	c1s = 0
	for i in s:
		if i == '1':
			c1s += 1
	c1t = 0
	for i in t:
		if i == '1':
			c1t += 1
	if c1s != c1t:
		return -1
	ones = 0
	zeros = 0
	for i in range(n):
		if s[i] == '1' and t[i] == '0':
			if zeros:
				zeros -= 1
			ones += 1
		elif s[i] == '0' and t[i] == '1':
			if ones:
				ones -= 1
			zeros += 1
	return zeros + ones
n = int(input())
s = input()
t = input()
print(answer(n, s, t))


n = int(input())
s1 = list(input())
s2 = list(input())
o1 = s1.count('1')
o2 = s2.count('1')
ans1 = ans2 = 0
if o1 != o2:
	print(-1)
else:
	zer = one = 0
	for i in range(n):
		if s1[i] != s2[i]:
			if s1[i] == '0':
				if one > 0:
					one -= 1
				else:
					zer += 1
					ans1 = max(ans1, zer)
			elif zer > 0:
				zer -= 1
			else:
				one += 1
				ans2 = max(ans2, one)
	print(ans1 + ans2)


for _ in range(1):
	n = input()
	s = input()
	t = input()
	a = ''
	c_s = 0
	c_t = 0
	if 1:
		(accept_0, accept_1) = (0, 0)
		for x in range(len(s)):
			if s[x] == '1':
				c_s += 1
			if t[x] == '1':
				c_t += 1
			if s[x] == t[x]:
				continue
			elif s[x] == '1':
				if accept_0 > 0:
					accept_0 -= 1
				accept_1 += 1
			else:
				if accept_1 > 0:
					accept_1 -= 1
				accept_0 += 1
		if c_s != c_t:
			print(-1)
		else:
			print(accept_1 + accept_0)


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1') or s.count('0') != t.count('0'):
	print(-1)
	exit(0)
(ones, zeroes) = ([], [])
ss = 0
for i in range(0, n):
	if s[i] == '0' and t[i] == '1':
		if len(ones) == 0:
			ss += 1
			zeroes.append(i)
		else:
			k = ones.pop()
			zeroes.append(k)
	if s[i] == '1' and t[i] == '0':
		if len(zeroes) == 0:
			ss += 1
			ones.append(i)
		else:
			k = zeroes.pop()
			ones.append(k)
print(ss)


n = int(input())
a = input()
b = input()
diff = 0
maxDiff = 0
minDiff = 0
for i in range(n):
	if a[i] == '1':
		diff += 1
	if b[i] == '1':
		diff -= 1
	if diff > maxDiff:
		maxDiff = diff
	if diff < minDiff:
		minDiff = diff
if diff != 0:
	print(-1)
else:
	print(maxDiff - minDiff)


rr = lambda : input().strip()
rri = lambda : int(stdin.readline())
rrm = lambda : [int(x) for x in rr().split()]
from sys import stdin, stdout

def sol():
	n = rri()
	s = rr()
	t = rr()
	cnt = 0
	mn = 0
	mx = 0
	for i in range(n):
		if s[i] == '1':
			cnt += 1
		if t[i] == '1':
			cnt -= 1
		mn = min(mn, cnt)
		mx = max(mx, cnt)
	if cnt != 0:
		print(-1)
	else:
		print(mx - mn)
	return
sol()


import os
import sys
if os.path.exists('/mnt/c/Users/Square/square/codeforces'):
	f = iter(open('E.txt').readlines())

	def input():
		return next(f).strip()
else:
	input = lambda : sys.stdin.readline().strip()
fprint = lambda *args: print(*args, flush=True)
n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
else:
	cur = 0
	ms = []
	for i in range(n):
		if s[i] != t[i]:
			if s[i] == '1':
				cur += 1
			else:
				cur -= 1
		ms.append(cur)
	print(max(ms) - min(ms))


n = int(input())
s = input()
t = input()
count1 = 0
count2 = 0
for i in s:
	if i == '1':
		count1 += 1
for i in t:
	if i == '1':
		count2 += 1
if count1 != count2:
	print(-1)
else:
	l = []
	for i in range(n):
		if s[i] != t[i]:
			if s[i] == '1':
				l.append(1)
			else:
				l.append(-1)
	if l == []:
		print(0)
		exit()
	n = len(l)
	ans = 0
	dp = [0 for i in range(n)]
	dp[0] = l[0]
	for i in range(1, n):
		dp[i] = max(dp[i - 1] + l[i], l[i])
	ans = max(dp)
	for i in range(n):
		if l[i] == 1:
			l[i] = -1
		else:
			l[i] = 1
	dp = [0 for i in range(n)]
	dp[0] = l[0]
	for i in range(1, n):
		dp[i] = max(dp[i - 1] + l[i], l[i])
	ans = max(ans, max(dp))
	print(ans)


def max_subarray_sum(x):
	cur = 0
	mx = 0
	for i in p:
		cur += x * i
		mx = max(mx, cur)
		if cur < 0:
			cur = 0
	return mx
n = int(input())
a = input().strip()
b = input().strip()
p = []
s = 0
for i in range(n):
	if a[i] != b[i]:
		if a[i] == '1':
			p.append(1)
			s += 1
		else:
			p.append(-1)
			s -= 1
if s != 0:
	print(-1)
else:
	print(max(max_subarray_sum(1), max_subarray_sum(-1)))


n = int(input())
(s, t) = (input().strip(), input().strip())
(now, ma, mi) = (0, 0, 0)
for i in range(n):
	if s[i] == t[i]:
		continue
	if s[i] == '1':
		now += 1
		ma = max(ma, now)
	else:
		now -= 1
		mi = min(mi, now)
print(ma - mi if now == 0 else -1)


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def get(A, x):
	(curr, mx) = (0, 0)
	for v in A:
		curr += x * v
		mx = max(mx, curr)
		if curr < 0:
			curr = 0
	return mx

def solve(N, S, T):
	A = []
	for (s, t) in zip(S, T):
		if s != t:
			if s == 1:
				A.append(1)
			else:
				A.append(-1)
	if sum(A or [0]) != 0:
		return -1
	return max(get(A, 1), get(A, -1))
N = int(input())
S = [int(x) for x in list(input())]
T = [int(x) for x in list(input())]
print(solve(N, S, T))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
	return input().decode().strip()

def rint():
	return map(int, input().split())

def oint():
	return int(input())
n = oint()
s = get_str()
t = get_str()
b = []
for i in range(n):
	if s[i] == t[i]:
		continue
	if s[i] == '0':
		b.append(-1)
	else:
		b.append(1)
if sum(b) != 0:
	print(-1)
else:
	h = 0
	max_h = 0
	min_h = 0
	for bb in b:
		h += bb
		max_h = max(max_h, h)
		min_h = min(min_h, h)
	print(abs(max_h - min_h))


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1') or s.count('0') != t.count('0'):
	print('-1')
else:
	sum = 0
	maxsum = 0
	minsum = 0
	for i in range(n):
		if s[i] == t[i]:
			continue
		if s[i] == '1':
			sum += 1
		elif s[i] == '0':
			sum -= 1
		if sum > maxsum:
			maxsum = sum
		if sum < minsum:
			minsum = sum
	print(maxsum - minsum)


(m1, m2, bal) = (0, 0, 0)
n = int(input())
a = input()
b = input()
for i in range(n):
	bal += int(a[i])
	bal -= int(b[i])
	m1 = max(m1, bal)
	m2 = min(m2, bal)
ans = -1 if bal != 0 else m1 - m2
print(ans)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, gcd
from collections import deque
n = int(input())
s = list(input())
t = list(input())
o = 0
z = 0
x = []
for i in range(n):
	if s[i] == '1':
		o += 1
	else:
		z += 1
	if t[i] == '1':
		o -= 1
	else:
		z -= 1
if z == 0 and o == 0:
	st1 = []
	st2 = []
	for i in range(n):
		if s[i] == '1' and t[i] == '0':
			if len(st1) == 0:
				x.append([i])
				st2.append(len(x) - 1)
			else:
				ne = st1.pop()
				x[ne].append(i)
				st2.append(ne)
		elif s[i] == '0' and t[i] == '1':
			if len(st2) == 0:
				x.append([i])
				st1.append(len(x) - 1)
			else:
				ne = st2.pop()
				x[ne].append(i)
				st1.append(ne)
	print(len(x))
else:
	print(-1)


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
n = Int()
a = [int(i) for i in input()]
b = [int(i) for i in input()]
have = []
for i in range(n):
	if a[i] != b[i]:
		have.append(b[i])
ans = 0
need = defaultdict(int)
flag = [0, 0]
for i in have:
	if need[i] == 0:
		need[i ^ 1] += 1
		ans += 1
		flag[i] += 1
	else:
		need[i ^ 1] += 1
		need[i] -= 1
		if flag[i ^ 1]:
			flag[i ^ 1] -= 1
if flag == [0, 0]:
	print(ans)
else:
	print(-1)


n = int(input())
s1 = input()
s2 = input()
dp = [False for i in range(n)]
end = False
if s1.count('1') != s2.count('1') or s1.count('0') != s2.count('0'):
	print(-1)
else:
	(zero, one) = (0, 0)
	for i in range(n):
		if s1[i] == '1' and s2[i] == '0':
			if zero:
				zero -= 1
			one += 1
		elif s1[i] == '0' and s2[i] == '1':
			if one:
				one -= 1
			zero += 1
	print(one + zero)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
n = II()
s = SI()
t = SI()
if sorted(s) != sorted(t):
	print(-1)
elif s == t:
	print(0)
else:
	l = []
	for i in range(n):
		if s[i] != t[i]:
			l.append(s[i])
	count = 0
	x = 0
	y = 0
	for i in range(1, len(l)):
		if l[i] == '1':
			count += 1
		else:
			count -= 1
		x = max(x, count)
		y = min(y, count)
	print(x - y)


import sys
import math
from decimal import *

def I():
	return int(sys.stdin.readline())

def IL():
	return list(map(int, sys.stdin.readline().strip().split()))

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))

def check(flip):
	cnt = 0
	f = flip.copy()
	while True:
		xx = 0
		turn = None
		for i in range(len(f)):
			x = f[i]
			if x == None:
				continue
			if turn == None:
				f[i] = None
				xx += 1
				turn = x ^ 1
			elif turn == x:
				xx += 1
				turn = x ^ 1
				f[i] = None
		if xx > 0:
			cnt += 1
		else:
			break
	return cnt

class Node:

	def __init__(self, x):
		self.x = x
		self.next = None
		self.prev = None

	def delete(self):
		nxt = self.next
		if self.prev != None:
			self.prev.next = self.next
		if self.next != None:
			self.next.prev = self.prev
		return nxt

def solve():
	n = I()
	s = input()
	t = input()
	sze = sum([1 for x in s if x == '0'])
	son = sum([1 for x in s if x == '1'])
	tze = sum([1 for x in t if x == '0'])
	ton = sum([1 for x in t if x == '1'])
	if sze != tze or son != ton:
		print(-1)
		return
	flip = [int(s[i]) for i in range(len(s)) if s[i] != t[i]]
	ans = 0
	ones = 0
	ze = 0
	for x in flip:
		if x == 1:
			if ze <= 0:
				ans += 1
			else:
				ze -= 1
			ones += 1
		else:
			if ones <= 0:
				ans += 1
			else:
				ones -= 1
			ze += 1
	print(ans)
solve()


(N,) = map(int, input().split())
s = input().strip()
t = input().strip()
x = y = mx = mn = c = 0
for i in range(N):
	if s[i] == t[i]:
		continue
	if s[i] == '1':
		c += 1
		x += 1
	else:
		c -= 1
		y += 1
	mx = max(c, mx)
	mn = min(c, mn)
if x != y:
	print(-1)
else:
	print(mx - mn)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = 1
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	start = {}
	for test in range(tests):
		n = inp()
		s = insr()
		t = insr()
		n_0t = 0
		n_1t = 0
		n_0s = 0
		n_1s = 0
		for i in range(n):
			if int(s[i]) == 1:
				n_1s += 1
			else:
				n_0s += 1
			if int(t[i]) == 1:
				n_1t += 1
			else:
				n_0t += 1
		if n_0s != n_0t or n_1s != n_1t:
			print(-1)
			continue
		one = 0
		zero = 0
		ans = 0
		for i in range(n):
			if s[i] != t[i]:
				if s[i] == '0':
					one = one + 1
					zero = max(zero - 1, 0)
				elif s[i] == '1':
					one = max(one - 1, 0)
					zero = zero + 1
			ans = max(ans, one, zero)
		print(ans)
main()


from sys import stdin, stdout
n = int(stdin.readline())
s = stdin.readline().strip()
t = stdin.readline().strip()

def binary_subsequence_rotation(n, s, t):
	scnt0 = 0
	scnt1 = 0
	tcnt0 = 0
	tcnt1 = 0
	for i in range(n):
		if s[i] == '0':
			scnt0 += 1
		else:
			scnt1 += 1
		if t[i] == '0':
			tcnt0 += 1
		else:
			tcnt1 += 1
	if scnt0 != tcnt0 or scnt1 != tcnt1:
		return -1
	tl0 = 0
	tl1 = 0
	for i in range(n):
		if s[i] == t[i]:
			continue
		if s[i] == '1':
			if tl0 == 0:
				tl1 += 1
			else:
				tl0 -= 1
				tl1 += 1
		elif tl1 == 0:
			tl0 += 1
		else:
			tl1 -= 1
			tl0 += 1
	return tl0 + tl1
print(str(binary_subsequence_rotation(n, s, t)))


import os
import sys
from io import BytesIO, IOBase
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
	n = int(input())
	s = input()
	t = input()
	count = [0] * 2
	for i in s:
		count[int(i)] += 1
	for i in t:
		count[int(i)] -= 1
	if count != [0, 0]:
		print(-1)
		continue
	c = -1
	(zero, one) = (0, 0)
	ans = 0
	for i in range(n):
		if s[i] != t[i]:
			c += 1
			if s[i] == '0':
				if zero:
					zero -= 1
				one += 1
			else:
				if one:
					one -= 1
				zero += 1
			ans = max(ans, zero + one)
	c += 1
	print(ans)


n = int(input())
s = [ord(x) - ord('0') for x in input()]
t = [ord(x) - ord('0') for x in input()]
if sum(s) != sum(t):
	print(-1)
else:
	(cur, mx, mn) = (0, 0, 0)
	for i in range(n):
		cur += s[i] - t[i]
		mx = max(mx, cur)
		mn = min(mn, cur)
	print(mx - mn)


n = int(input())
ar1 = list(map(int, input()))
ar2 = list(map(int, input()))
if ar1.count(1) != ar2.count(1):
	print(-1)
else:
	cnt = 0
	ans1 = 0
	ans2 = 0
	for i in range(n):
		if ar1[i] == 1 and ar2[i] == 0:
			cnt += 1
		elif ar1[i] == 0 and ar2[i] == 1:
			cnt -= 1
		ans1 = max(cnt, ans1)
		ans2 = min(cnt, ans2)
	print(ans1 - ans2)


import math

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b / gcd(a, b)

def bs(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return arr[mid]
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def swap(list, pos1, pos2):
	(list[pos1], list[pos2]) = (list[pos2], list[pos1])
	return list
n = int(input())
s = input()
t = input()
cs = s.count('1')
ct = t.count('1')
if cs != ct:
	print(-1)
else:
	c = 0
	y01 = 0
	y10 = 0
	x01 = 0
	x10 = 0
	for i in range(n):
		if s[i] == '0' and t[i] == '1':
			x01 += 1
			y01 += 1
			if y10 > 0:
				y10 -= 1
			else:
				c += 1
		elif s[i] == '1' and t[i] == '0':
			x10 += 1
			y10 += 1
			if y01 > 0:
				y01 -= 1
			else:
				c += 1
	if x01 != x10:
		print(-1)
	else:
		print(c)


import os
import sys
from io import BytesIO, IOBase
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	n = N()
	(s, t) = (input(), input())
	ct = 0
	arr = []
	for i in range(n):
		if s[i] == '1':
			ct += 1
		if t[i] == '1':
			ct -= 1
		arr.append(ct)
	print(-1 if ct != 0 else max(arr) - min(arr))
main()


def solve(arr):
	mx = 0
	curr = 0
	for i in range(len(arr)):
		if curr < 0:
			curr = 0
		if arr[i] == 1:
			curr = curr + 1
		else:
			curr = curr - 1
		mx = max(curr, mx)
	return mx

def solve_1(arr):
	mx = 0
	curr = 0
	for i in range(len(arr)):
		if curr < 0:
			curr = 0
		if arr[i] == 0:
			curr = curr + 1
		else:
			curr = curr - 1
		mx = max(curr, mx)
	return mx
n = int(input())
str_1 = str(input())
str_2 = str(input())
count_1 = 0
count_2 = 0
ind_10 = []
for i in range(n):
	if str_1[i] == '1':
		count_1 = count_1 + 1
	if str_2[i] == '1':
		count_2 = count_2 + 1
if count_1 != count_2:
	print('-1')
else:
	for i in range(n):
		if str_1[i] == '1' and str_2[i] == '0':
			ind_10.append(1)
		if str_2[i] == '1' and str_1[i] == '0':
			ind_10.append(0)
	count = solve(ind_10)
	count_f = solve_1(ind_10)
	print(max(count, count_f))


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
n = int(input())
s = input()
t = input()
s1 = 0
t1 = 0
l = [0] * n
for j in range(n):
	if s[j] == '1':
		s1 += 1
		if t[j] == '0':
			l[j] = 1
	if t[j] == '1':
		if s[j] == '0':
			l[j] = -1
		t1 += 1
if s1 != t1:
	print(-1)
else:
	c = 0
	c1 = 0
	sum = 0
	ans1 = 0
	ans2 = 0
	for j in l:
		c += j
		c1 += -j
		c = max(c, 0)
		c1 = max(c1, 0)
		ans1 = max(ans1, c)
		ans2 = max(ans2, c1)
	print(max(ans1, ans2))


import sys
import math
input = sys.stdin.readline
t = int(input())
a = list(input().rstrip())
b = list(input().rstrip())
if a.count('1') != b.count('1'):
	print(-1)
else:
	nums = []
	running = 0
	for i in range(len(a)):
		if a[i] == '1':
			running += 1
		if b[i] == '1':
			running -= 1
		nums.append(running)
	print(max(nums) - min(nums))


n = int(input())
first_string = list(input())
second_string = list(input())
a = 0
b = 0
final_answer = 0
for i in range(n):
	if first_string[i] == '1':
		a = a + 1
	else:
		b = b + 1
	if second_string[i] == '1':
		a = a - 1
	else:
		b = b - 1
one_zero = []
zero_one = []
if a == 0 and b == 0:
	for i in range(n):
		if first_string[i] == '1' and second_string[i] == '0':
			if len(one_zero) == 0:
				final_answer += 1
				zero_one.append(final_answer)
			else:
				poped = one_zero.pop()
				zero_one.append(poped)
		elif first_string[i] == '0' and second_string[i] == '1':
			if len(zero_one) == 0:
				final_answer += 1
				one_zero.append(final_answer)
			else:
				poped = zero_one.pop()
				one_zero.append(poped)
else:
	final_answer = -1
print(final_answer)


import sys

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
N = INT()
S = input()
T = input()
if S.count('0') != T.count('0'):
	print(-1)
	exit()
S2 = []
for i in range(N):
	if S[i] != T[i]:
		S2.append(S[i])
ans = 0
cnt0 = cnt1 = 0
for s in S2:
	if s == '0':
		cnt0 += 1
		cnt1 -= 1
	else:
		cnt0 -= 1
		cnt1 += 1
	cnt0 = max(cnt0, 0)
	cnt1 = max(cnt1, 0)
	ans = max(ans, cnt0, cnt1)
print(ans)


n = input()
s = input()
t = input()
zero = 0
mmax = 0
mmin = 0
for i in range(len(s)):
	if s[i] != t[i]:
		if s[i] == '0':
			zero = zero + 1
		else:
			zero = zero - 1
		mmax = max(zero, mmax)
		mmin = min(zero, mmin)
if zero == 0:
	print(mmax - mmin)
else:
	print(-1)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

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

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

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

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

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

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

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = 1
for i in range(t):
	n = N()
	s = input()
	t = input()
	cnt = 0
	res = []
	for i in range(n):
		if s[i] != t[i]:
			if s[i] == '1':
				cnt += 1
			else:
				cnt -= 1
			res.append(1 if s[i] == '1' else -1)
	if cnt != 0:
		print(-1)
	else:
		n = len(res)
		ans = 0
		a = b = 0
		for i in range(n):
			if res[i] == 1:
				a = max(a, 0) + 1
				b = min(b, 0) + 1
			else:
				a = max(a, 0) - 1
				b = min(b, 0) - 1
			ans = max(ans, abs(a), abs(b))
		print(ans)


import sys
input = sys.stdin.readline
n = int(input())
s = input()
t = input()
v = 0
s1 = 0
t1 = 0
stype1 = 0
stype2 = 0
for i in range(n):
	if s[i] == t[i]:
		v += 1
	if s[i] == '1' and t[i] == '0':
		stype1 += 1
		stype2 = max(0, stype2 - 1)
	elif s[i] == '0' and t[i] == '1':
		stype2 += 1
		stype1 = max(0, stype1 - 1)
	if s[i] == '1':
		s1 += 1
	if t[i] == '1':
		t1 += 1
if v == n:
	print(0)
elif s1 != t1:
	print(-1)
else:
	print(stype1 + stype2)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n,) = I()
s = input().strip()
t = input().strip()
if s.count('1') != t.count('1'):
	print(-1)
else:
	an = 0
	if s == t:
		print(an)
	else:
		a = b = 0
		for i in range(n):
			if s[i] != t[i]:
				if s[i] == '1':
					if b:
						b -= 1
					else:
						an += 1
					a += 1
				else:
					if a:
						a -= 1
					else:
						an += 1
					b += 1
		print(an)


import sys
import math
import collections
import heapq

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_input():
	return list(map(int, input().split()))

def get(x):
	cur = 0
	mx = 0
	for i in range(1, len(s) + 1):
		cur += x * a[i]
		mx = max(mx, cur)
		if cur < 0:
			cur = 0
	return mx
t = 1
for ti in range(1, t + 1):
	n = int(input())
	s = input()
	t = input()
	sc = collections.Counter(s)
	tc = collections.Counter(t)
	if sc['0'] != tc['0'] or sc['1'] != tc['1']:
		print(-1)
	else:
		a = [0] * (len(s) + 1)
		count = 0
		for i in range(1, len(s) + 1):
			if s[i - 1] != t[i - 1]:
				if s[i - 1] == '1':
					a[i] = 1
				else:
					a[i] = -1
			count += a[i]
		print(max(get(1), get(-1)))


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def solve():
	n = input(11)
	s = input(4)
	t = input(4)
	log(s)
	log(t)
	b = [j for (i, j) in enu(s) if j != t[i]]
	u = [0, 0]
	for i in b:
		u[i] += 1
	if u[0] != u[1]:
		out(-1)
		return
	m = 0
	for j in (1, -1):
		c = 0
		for i in b:
			if i:
				c += j
			else:
				c -= j
			if c < 0:
				c = 0
			m = max(m, abs(c))
	out(m)
	return
solve()


n = int(input())
(a, b) = (input(), input())
if sorted(a) != sorted(b):
	print(-1)
	exit(0)
_00 = _01 = _10 = _11 = 0
for i in range(n):
	if a[i] == b[i]:
		continue
	if a[i] == '0':
		if _11 > 0:
			_11 -= 1
			_10 += 1
		elif _01 > 0:
			_01 -= 1
			_00 += 1
		else:
			_00 += 1
	elif _00 > 0:
		_00 -= 1
		_01 += 1
	elif _10 > 0:
		_10 -= 1
		_11 += 1
	else:
		_11 += 1
if _11 != 0 or _00 != 0:
	print(-1)
else:
	print(_01 + _10)


n = int(input())
a = input()
b = input()
ans = 0
cnt = 0
df = 0
temp = []
if a != b:
	for i in range(n):
		if a[i] != b[i]:
			if a[i] == '1':
				if df == ans:
					ans = ans + 1
					df = df + 1
				else:
					df = df + 1
				cnt = cnt + 1
			else:
				cnt = cnt - 1
				if df > 0:
					df = df - 1
				else:
					ans = ans + 1
print(ans if cnt == 0 else -1)


import sys
input = sys.stdin.buffer.readline
N = int(input())
S = list(input().rstrip())
T = list(input().rstrip())

def clean(P):
	if not P:
		return P
	pre = P[0]
	tmp = 0
	ret = []
	for p in P:
		if p * pre < 0:
			ret.append(tmp)
			tmp = p
		else:
			tmp += p
		pre = p
	if P[-1] * P[0] > 0:
		if ret:
			ret[0] += tmp
		else:
			ret.append(tmp)
	else:
		ret.append(tmp)
	return ret
P = []
for (i, (s, t)) in enumerate(zip(S, T)):
	if s > t:
		P.append(+1)
	elif s < t:
		P.append(-1)
if not P:
	ans = 0
elif sum(P) != 0:
	ans = -1
else:
	P = clean(P)
	ans = 0
	while P:
		ans += 1
		nP = []
		for p in P:
			if p > 1:
				nP.append(p - 1)
			elif p < -1:
				nP.append(p + 1)
		P = clean(nP)
print(ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
n = int(input())
s = input()
t = input()
l = []
for i in range(n):
	l.append(int(s[i]) - int(t[i]))
if sum(l) != 0:
	print(-1)
else:
	ma = max(0, l[0])
	mi = min(0, l[0])
	cur = l[0]
	ans = max(l[0], 0)
	for i in range(1, n):
		cur += l[i]
		ans = max(ans, abs(cur - ma), abs(cur - mi))
		ma = max(cur, ma)
		mi = min(cur, mi)
	print(ans)


n = int(input())
a = input()
a = [int(i) for i in a]
b = input()
b = [int(i) for i in b]
li = []
for i in range(n):
	if a[i] != b[i]:
		li.append(a[i])
c = 0
c0 = 0
c1 = 0
a.sort()
b.sort()
if a != b:
	print(-1)
else:
	for i in range(len(li)):
		if li[i] == 1:
			c1 += 1
			if c0 != 0:
				c0 -= 1
			else:
				c += 1
		else:
			c0 += 1
			if c1 != 0:
				c1 -= 1
			else:
				c += 1
	print(c)


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
n = fi()
a = si()
b = si()
d = []
for i in range(n):
	if a[i] != b[i]:
		d.append(1 if a[i] == '1' else -1)
maxi = 0
i = c = 0
d += d
for i in range(len(d)):
	c += d[i]
	maxi = max(maxi, c)
	if c < 0:
		c = 0
print(maxi if a.count('1') == b.count('1') else -1)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def main():
	n = int(input())
	s = input()
	t = input()
	(o, z) = (0, 0)
	a = 0
	if s == t:
		print(0)
	elif s.count('1') != t.count('1'):
		print(-1)
	else:
		for i in range(n):
			a += int(s[i]) - int(t[i])
			o = max(a, o)
			z = min(a, z)
		print(o - z)
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


q = int(input())
w = input()
e = input()
r = []
if w.count('1') != e.count('1'):
	print(-1)
	exit()
if w.count('1') == q or w.count('1') == 0:
	print(0)
	exit()
for i in range(q):
	if w[i] != e[i]:
		r.append(e[i])
k = 0
l = []
for i in r:
	if i == '1':
		k += 1
	else:
		k -= 1
	l.append(k)
print(max(l) + abs(min(l)))


n = int(input())
(s, t) = (input(), input())
(mx, mn, bal) = (-1, 10 ** 9, 0)
for i in range(n):
	bal += ord(s[i]) - ord('0')
	bal -= ord(t[i]) - ord('0')
	mx = max(mx, bal)
	mn = min(mn, bal)
print(-1 if bal != 0 else mx - mn)


n = int(input())
s = input()
t = input()
(o, z) = (0, 0)
a = 0
if s == t:
	print(0)
elif s.count('1') != t.count('1'):
	print(-1)
else:
	for i in range(n):
		a += int(s[i]) - int(t[i])
		o = max(a, o)
		z = min(a, z)
	print(o - z)


def solve(n, s, t):
	maxi = 0
	mini = 0
	summ = 0
	for i in range(n):
		summ += int(s[i]) - int(t[i])
		if summ > maxi:
			maxi = summ
		if summ < mini:
			mini = summ
	if summ != 0:
		print(-1)
	else:
		print(maxi - mini)
n = int(input())
s = input()
t = input()
solve(n, s, t)


def maxx(a, x):
	p = 0
	count = 0
	for i in a:
		p += x * i
		count = max(count, p)
		if p < 0:
			p = 0
	return count
n = int(input())
s = str(input())
t = str(input())
a = []
to = 0
tno = 0
if s == t:
	print(0)
else:
	for i in range(n):
		if s[i] == '1' and t[i] == '0':
			a.append(1)
		if s[i] == '0' and t[i] == '1':
			a.append(-1)
	if sum(a) != 0:
		print(-1)
	else:
		print(max(maxx(a, -1), maxx(a, 1)))


n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
	print(-1)
else:
	fpat = 0
	spat = 0
	for i in range(n):
		if s[i] == '0' and t[i] == '1':
			if fpat > 0:
				fpat = fpat - 1
			spat = spat + 1
		elif t[i] == '0' and s[i] == '1':
			if spat > 0:
				spat = spat - 1
			fpat = fpat + 1
	print(spat + fpat)


import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
from bisect import bisect_right
from collections import deque
from math import gcd
mod = 998244353

def main():
	for _ in range(1):
		n = int(input())
		s = input()
		t = input()
		c1 = 0
		c2 = 0
		b = True
		for i in range(n):
			if s[i] == '1':
				c1 += 1
			if t[i] == '1':
				c2 += 1
			if c2 > c1:
				b = False
		if True:
			cnt = 0
			b = 0
			a = [0] * n
			for i in range(n):
				if s[i] == '1' and t[i] == '0':
					a[i] = 1
				if s[i] == '0' and t[i] == '1':
					a[i] = -1
			l = 0
			r = n
			prev = -1
			while l <= r:
				mid = l + (r - l) // 2
				c = mid
				b = True
				c1 = 0
				s1 = 0
				s_1 = 0
				c_1 = 0
				for i in a:
					if i == 1:
						if c_1 == 0:
							s1 += 1
							c -= 1
						else:
							c_1 -= 1
						c1 += 1
					elif i == -1:
						if c1 == 0:
							s_1 += 1
							c -= 1
						else:
							c1 -= 1
						c_1 += 1
					if c < 0:
						b = False
						break
				if b and c + c1 + c_1 == mid and (s1 == c_1) and (s_1 == c1):
					prev = mid
					r = mid - 1
				else:
					l = mid + 1
			print(prev)
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


inputlen = int(input())
input1 = input()
input2 = input()
diff = []
for i in range(inputlen):
	if input1[i] != input2[i]:
		diff.append(input1[i])
if len(diff) == 0:
	print(0)
elif diff.count('0') != diff.count('1'):
	print(-1)
else:
	maxlen0 = 0
	maxlen1 = 0
	curlen0 = 0
	curlen1 = 0
	for i in range(len(diff)):
		if diff[i] == '0':
			curlen0 += 1
			maxlen0 = max(maxlen0, curlen0)
			curlen1 = max(curlen1 - 1, 0)
		if diff[i] == '1':
			curlen1 += 1
			maxlen1 = max(maxlen1, curlen1)
			curlen0 = max(curlen0 - 1, 0)
	i = -1
	while diff[i] == diff[i + 1]:
		if diff[i] == '0':
			curlen0 += 1
			maxlen0 = max(maxlen0, curlen0)
			curlen1 = max(curlen1 - 1, 0)
		if diff[i] == '1':
			curlen1 += 1
			maxlen1 = max(maxlen1, curlen1)
			curlen0 = max(curlen0 - 1, 0)
		i += 1
	print(max(maxlen1, maxlen0))


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	s = insr() * 2
	t = insr() * 2
	if s.count('1') != t.count('1'):
		print(-1)
		return
	q = 0
	w = 0
	for i in range(len(s)):
		if s[i] != t[i]:
			if s[i] == '1':
				q = q + 1
			else:
				q = max(0, q - 1)
			w = max(w, q)
	print(w)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = (q[a[i] - 1], 1)
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


input()
s0 = input()
s1 = input()
if s0.count('1') != s1.count('1'):
	print(-1)
else:
	m0 = 0
	m1 = 0
	v0 = 0
	v1 = 0
	for (i, j) in zip(s0, s1):
		if i != j:
			v0 += 1 if i == '1' else -1
			v1 += 1 if j == '1' else -1
			m0 = max(v0, m0)
			m1 = max(v1, m1)
	print(m0 + m1)


import sys
from bisect import bisect_left
from collections import defaultdict
input = lambda : sys.stdin.readline().rstrip()
R = lambda : map(int, input().split())

def readint():
	return [int(w) for w in input().split()]
(n,) = readint()
s = input()
t = input()
pre = 0
mn = n + 5
mx = 0
for (i, j) in zip(s, t):
	if i > j:
		pre += 1
	elif i < j:
		pre -= 1
	mn = min(mn, pre)
	mx = max(mx, pre)
if pre != 0:
	print(-1)
else:
	print(mx - mn)


import sys
import heapq
import random
import collections

def maxSubArraySum(arr):
	max_so_far = 0
	max_ending_here = 0
	for a in arr:
		max_ending_here = max_ending_here + a
		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

def solve(arr, brr):
	console('----- solving ------')
	ar = []
	br = []
	if collections.Counter(arr)['0'] != collections.Counter(brr)['0']:
		return -1
	for (a, b) in zip(arr, brr):
		if a == b:
			continue
		ar.append(2 * int(a) - 1)
		br.append(2 * int(b) - 1)
	return max(maxSubArraySum(ar), maxSubArraySum(br))

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
_ = int(input())
arr = input()
brr = input()
res = solve(arr, brr)
assert res == solve(brr, arr)
print(res)


import math
import sys
n = int(input())
t1 = list(input())
t3 = list(input())
o = 0
z = 0
i = 0
t2 = []
while i < len(t1):
	if t1[i] == t3[i]:
		i += 1
	else:
		if t1[i] == '1':
			o += 1
			t2.append(t3[i])
		else:
			z += 1
			t2.append(t3[i])
		i += 1
if len(t2) == 0:
	print('0')
	sys.exit()
for i in range(len(t2)):
	if t2[i] == '0':
		z -= 1
	else:
		o -= 1
if o < 0 or z < 0:
	print('-1')
	sys.exit()
else:
	ma = 0
	m = 0
	for i in t2:
		if int(i) % 2 == 0:
			m += 1
			ma = max(ma, m)
		else:
			m = max(0, m - 1)
			ma = max(m, ma)
	m = 0
	for i in t2:
		if int(i) % 2 == 1:
			m += 1
			ma = max(ma, m)
		else:
			m = max(0, m - 1)
			ma = max(m, ma)
	print(ma)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, S, T):
	S0 = S.count('0')
	T0 = T.count('0')
	S1 = S.count('1')
	T1 = T.count('1')
	if S0 != T0 or S1 != T1:
		return -1
	consect = []
	for (s, t) in zip(S, T):
		if s != t:
			if not consect:
				consect.append([s, 1])
			elif consect[-1][0] == s:
				consect[-1][1] += 1
			else:
				consect.append([s, 1])
	steps = 0
	while consect:
		nextConsect = []
		for (ch, count) in consect:
			if count > 1:
				if not nextConsect:
					nextConsect.append([ch, count - 1])
				elif nextConsect[-1][0] == ch:
					nextConsect[-1][1] += count - 1
				else:
					nextConsect.append([ch, count - 1])
		consect = nextConsect
		steps += 1
	return steps
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
S = input().decode().rstrip()
T = input().decode().rstrip()
ans = solve(N, S, T)
print(ans)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def main():
	n = int(inputi())
	ss = [int(a) for a in input()]
	tt = [int(a) for a in input()]
	if sum(ss) != sum(tt):
		print(-1)
		return
	c = 0
	mxc = 0
	mnc = 0
	for i in range(n):
		if ss[i % n] == tt[i % n]:
			continue
		c += ss[i % n] - tt[i % n]
		mxc = max(c, mxc)
		mnc = min(c, mnc)
	print(mxc - mnc)
main()


from sys import stdin
n = int(stdin.readline().strip())
s = stdin.readline().strip()
t = stdin.readline().strip()
(lvl, M0, M1, prev) = (0, 0, 0, None)
for i in range(n):
	if s[i] == t[i]:
		continue
	if not prev:
		prev = s[i]
		lvl = 1
	elif s[i] == prev:
		lvl += 1
	else:
		lvl -= 1
		if lvl == 0:
			prev = None
	if prev == '0':
		M0 = max(M0, lvl)
	else:
		M1 = max(M1, lvl)
if lvl > 0:
	print(-1)
else:
	print(M0 + M1)