#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <unordered_set>
//upper bound >
//lower bound >=
//int index = (lower_bound(testvec.begin(), testvec.end(), num)-testvec.begin());
using namespace std;
using ll = long long;
#define int ll
int mod = 1000000007;
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int c;
cin >> c;
vector<pair<int,int>> exp(c); //expReq, amount
for (size_t i = 0; i < c; i++)
{
int a;
cin >> a;
exp[i] = { a,0 };
}
for (size_t i = 0; i < c; i++)
{
int a;
cin >> a;
exp[i] = { exp[i].first,a };
}
sort(exp.begin(), exp.end());
int totalEllapsed = 0;
int fwindex = 0;
int bwindex = c - 1;
int curExp = 0;
while (true)
{
if (bwindex == fwindex) {
int expneeded = exp[fwindex].first - curExp;
if (expneeded < 0) expneeded = 0;
totalEllapsed += 2 * (expneeded);
curExp = exp[fwindex].first;
exp[fwindex] = { exp[fwindex].first,exp[fwindex].second - expneeded };
totalEllapsed += exp[fwindex].second;
cout << totalEllapsed;
return 0;
}
if (curExp >= exp[fwindex].first) {
totalEllapsed += exp[fwindex].second;
curExp += exp[fwindex].second;
exp[fwindex] = { exp[fwindex].first,0 };
fwindex++;
}
else {
if (exp[fwindex].first - curExp < exp[bwindex].second) {
totalEllapsed += 2 * (exp[fwindex].first - curExp);
exp[bwindex] = { exp[bwindex].first,exp[bwindex].second - (exp[fwindex].first - curExp) };
curExp = exp[fwindex].first;
}
else {
totalEllapsed += 2 * (exp[bwindex].second);
curExp += exp[bwindex].second;
exp[bwindex] = { exp[bwindex].first,0 };
bwindex--;
}
}
}
cout << totalEllapsed;
}