// Bài 5
#include <bits/stdc++.h>
using namespace std;
const __int128 INF = ((__int128)1 << 120);
const int BUF_SIZE = 1 << 20;
char buf[BUF_SIZE];
int buf_ptr = 0, buf_len = 0;
inline char getChar() {
if (buf_ptr >= buf_len) {
buf_ptr = 0;
buf_len = fread(buf, 1, BUF_SIZE, stdin);
if (buf_len == 0) return EOF;
}
return buf[buf_ptr++];
}
inline int readInt() {
int x = 0;
char c = getChar();
while (c < '0' || c > '9') {
if (c == EOF) return 0;
c = getChar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = getChar();
}
return x;
}
inline long long readLong() {
long long x = 0;
bool neg = false;
char c = getChar();
while (c < '0' || c > '9') {
if (c == '-') neg = true;
if (c == EOF) return 0;
c = getChar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = getChar();
}
return neg ? -x : x;
}
const uint32_t TABLE_SIZE = 1 << 23;
const uint64_t EMPTY = 0x7FFFFFFF7FFFFFFFULL;
inline uint32_t hash_f(int d1, int d2) {
uint64_t x = ((uint64_t)(uint32_t)d1 << 32) | (uint32_t)d2;
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9ULL;
x ^= x >> 27;
x *= 0x94d049bb133111ebULL;
x ^= x >> 31;
return x & (TABLE_SIZE - 1);
}
void print128(__int128 n) {
if (n < 0) {
cout << "-";
n = -n;
}
if (n > 9) print128(n / 10);
cout << (int)(n % 10);
}
int main() {
freopen("thatthach.inp","r",stdin);
freopen("thatthach.out","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n = readInt();
if (n == 0) return 0;
vector<uint8_t> t(n);
for (int i = 0; i < n; ++i) {
t[i] = (uint8_t)readInt();
}
vector<uint64_t> hash_key(TABLE_SIZE, EMPTY);
vector<__int128> hash_sum(TABLE_SIZE);
__int128 max_val = -INF;
bool found = false;
uint32_t h = hash_f(0, 0);
hash_key[h] = 0; // Key tương ứng với d1=0, d2=0
hash_sum[h] = 0;
int cntA = 0, cntB = 0, cntC = 0;
__int128 current_s = 0;
for (int i = 0; i < n; ++i) {
long long val_a = readLong();
if (t[i] == 0) cntA++;
else if (t[i] == 1) cntB++;
else if (t[i] == 2) cntC++;
current_s += val_a;
int d1 = cntB - cntA;
int d2 = cntC - cntB;
uint64_t cur_key = ((uint64_t)(uint32_t)d1 << 32) | (uint32_t)d2;
uint32_t curr_h = hash_f(d1, d2);
while (hash_key[curr_h] != EMPTY) {
if (hash_key[curr_h] == cur_key) {
__int128 potential_sum = current_s - hash_sum[curr_h];
if (potential_sum > max_val) {
max_val = potential_sum;
}
found = true;
if (current_s < hash_sum[curr_h]) {
hash_sum[curr_h] = current_s;
}
break;
}
curr_h = (curr_h + 1) & (TABLE_SIZE - 1);
}
if (hash_key[curr_h] == EMPTY) {
hash_key[curr_h] = cur_key;
hash_sum[curr_h] = current_s;
}
}
if (found) {
print128(max_val);
cout << "\n";
} else {
cout << "KHONG\n";
}
return 0;
}