It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.

There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i < j < k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i < s_j < s_k$ should be held.

The rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay.


-----Input-----

The first line contains a single integer $n$ ($3 \le n \le 3\,000$) — the number of displays.

The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^9$) — the font sizes on the displays in the order they stand along the road.

The third line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \le c_i \le 10^8$) — the rent costs for each display.


-----Output-----

If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices $i < j < k$ such that $s_i < s_j < s_k$.


-----Examples-----
Input
5
2 4 5 4 10
40 30 20 10 40

Output
90

Input
3
100 101 100
2 4 5

Output
-1

Input
10
1 2 3 4 5 6 7 8 9 10
10 13 11 14 15 12 13 13 18 13

Output
33



-----Note-----

In the first example you can, for example, choose displays $1$, $4$ and $5$, because $s_1 < s_4 < s_5$ ($2 < 4 < 10$), and the rent cost is $40 + 10 + 40 = 90$.

In the second example you can't select a valid triple of indices, so the answer is -1.

Difficulty: MEDIUM
Tags: Dynamic programming

Implementation

Complete search
Skill types: Dynamic programming

Complete search
Expected Time Complexity: O(N^2)

Starter code:

Solutions:
from math import inf
n = int(input())
s = list(map(int, input().split(' ')))
c = list(map(int, input().split(' ')))
dp = [[0, inf, inf, inf][:] for i in range(n)]
dp[0][1] = c[0]
for j in range(1, 4):
	for i in range(1, n):
		for k in reversed(range(i)):
			if j == 1 or s[k] < s[i]:
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + c[i])
r = min((x[3] for x in dp))
if r == inf:
	print(-1)
else:
	print(r)


from heapq import heappush
import bisect
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
a = {}
b = []
ak = []
aki = []
for i in range(n - 1, -1, -1):
	ind0 = bisect.bisect(ak, s[i])
	ak.insert(ind0, s[i])
	aki.insert(ind0, i)
	a[i] = []
	ind = -1
	for j in aki[ind0:]:
		if s[j] > s[i]:
			if len(a[j]) == 1:
				heappush(b, c[i] + c[j] + c[a[j][0]])
			if ind == -1 or m >= c[j]:
				(m, ind) = (c[j], j)
	if ind != -1:
		a[i] = [ind]
if b:
	print(b[0])
else:
	print(-1)


n = int(input())
a = [[int(i)] for i in input().split()]
b = [int(i) for i in input().split()]
for i in range(n):
	a[i].append(b[i])
del b
d = [0 for i in range(n)]
for i in range(1, n):
	mini = 0
	for j in range(i):
		if a[j][0] < a[i][0]:
			if mini == 0:
				mini = a[j][1]
			else:
				mini = min(mini, a[j][1])
	if mini:
		mini += a[i][1]
	d[i] = mini
c = [0 for i in range(n)]
for i in range(1, n):
	mini = 0
	if d[i]:
		for j in range(i + 1, n):
			if a[i][0] < a[j][0]:
				if mini == 0:
					mini = a[j][1]
				else:
					mini = min(mini, a[j][1])
	if mini:
		c[i] = d[i] + mini
c = [i for i in c if i > 0]
if len(c):
	print(min(c))
else:
	print('-1')


from bisect import bisect
n = int(input())
S = list(map(int, input().split()))
C = list(map(int, input().split()))

def insert_sign(S, C, s, c):
	pos_s = bisect(S, s)
	pos_c = bisect(C, c)
	if pos_s >= pos_c:
		S[pos_c:pos_s] = (s,)
		C[pos_c:pos_s] = (c,)

def minimal_rest_cost(S, C, s):
	pos = bisect(S, s)
	return C[pos]
MAX = 10 ** 10
(S1, C1) = [[MAX], [MAX]]
(S2, C2) = [[MAX], [MAX]]
(S3, C3) = [[MAX], [MAX]]
for (s, c) in zip(S[::-1], C[::-1]):
	insert_sign(S3, C3, s, c + minimal_rest_cost(S2, C2, s))
	insert_sign(S2, C2, s, c + minimal_rest_cost(S1, C1, s))
	insert_sign(S1, C1, s, c)
if C3[0] < MAX:
	print(C3[0])
else:
	print(-1)


from sys import *
from math import *
from bisect import *
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
m = []
c = []
for i in range(n):
	x = []
	l = max(b) + 1
	k = -1
	for j in range(i + 1, n):
		if a[j] > a[i]:
			x.append(j)
			if b[j] < l:
				l = b[j]
				k = j
	c.append(k)
	m.append(x)
ans = sum(b) + 1
for i in range(n - 1):
	x = b[i]
	for j in range(len(m[i])):
		y = b[m[i][j]]
		if c[m[i][j]] != -1:
			z = b[c[m[i][j]]]
			if x + y + z < ans:
				ans = x + y + z
if ans == sum(b) + 1:
	print(-1)
else:
	print(ans)


def fxn1(arr, ls, j, m1=10 ** 9):
	for i in range(0, j):
		if arr[i] < arr[j]:
			m1 = min(m1, ls[i])
	return m1

def fxn2(arr, ls, j, m2=10 ** 9):
	for k in range(j + 1, len(arr)):
		if arr[k] > arr[j]:
			m2 = min(m2, ls[k])
	return m2
t1 = 10 ** 9
t2 = 10 ** 9
z = 10 ** 9
n = int(input())
arr = list(map(int, input().split()))
ls = list(map(int, input().split()))
for j in range(1, n - 1):
	t1 = fxn1(arr, ls, j)
	t2 = fxn2(arr, ls, j)
	z = min(ls[j] + t1 + t2, z)
if z == 10 ** 9:
	print(-1)
else:
	print(z)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = 10000000000.0
for x in range(n):
	a = 10000000000.0
	b = 10000000000.0
	for i in range(x):
		if s[i] < s[x]:
			a = min(a, c[i])
	for i in range(x + 1, n):
		if s[i] > s[x]:
			b = min(b, c[i])
	if a < 10000000000.0 and b < 10000000000.0:
		ans = min(ans, a + b + c[x])
if ans == 10000000000.0:
	print('-1')
else:
	print(ans)


n = int(input())
ls1 = [int(i) for i in input().split()]
ls2 = [int(i) for i in input().split()]
ans = -1
for i in range(1, n - 1):
	l = [ls2[j] for j in range(0, i) if ls1[j] < ls1[i]]
	r = [ls2[j] for j in range(i + 1, n) if ls1[j] > ls1[i]]
	if len(l) and len(r):
		ans = min(l) + min(r) + ls2[i] if ans == -1 else min(ans, min(l) + min(r) + ls2[i])
print(ans)


from math import inf
n = int(input())
s = [int(e) for e in input().split()]
c = [int(e) for e in input().split()]
d = [[inf, inf] for i in range(n)]
for i in range(n):
	s1 = s[i]
	for j in range(i):
		if s[j] < s1:
			if c[j] < d[i][0]:
				d[i][0] = c[j]
			if d[j][0] < d[i][1]:
				d[i][1] = d[j][0]
	d[i][0] += c[i]
	d[i][1] += c[i]
m = min([e[1] for e in d])
print(m if m < inf else -1)


INF = 10000000000
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
min_v = INF
for j in range(1, n):
	left = INF
	for i in range(j):
		if s[j] > s[i]:
			left = min(left, c[i] + c[j])
	curr = INF
	for k in range(j + 1, n):
		if s[k] > s[j]:
			curr = min(curr, left + c[k])
	min_v = min(min_v, curr)
if min_v != INF:
	print(min_v)
else:
	print(-1)


ans = float('inf')
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
	b = -1
	c_ = c[i]
	for j in range(i):
		if s[j] >= s[i]:
			continue
		if b == -1 or c[b] > c[j]:
			b = j
	if b == -1:
		continue
	c_ += c[b]
	b = -1
	for j in range(i + 1, n):
		if s[j] <= s[i]:
			continue
		if b == -1 or c[b] > c[j]:
			b = j
	if b == -1:
		continue
	c_ += c[b]
	ans = min(ans, c_)
if ans == float('inf'):
	print(-1)
else:
	print(ans)


def go():
	n = int(input())
	s = [int(i) for i in input().split(' ')]
	c = [int(i) for i in input().split(' ')]
	m = float('inf')
	for j in range(1, n - 1):
		c_m = float('inf')
		for i in range(0, j):
			if s[i] < s[j]:
				if c[i] + c[j] < c_m:
					c_m = c[i] + c[j]
		for k in range(j + 1, n):
			if s[j] < s[k]:
				if c[k] + c_m < m:
					m = c_m + c[k]
	return m if m != float('inf') else -1
print(go())


from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def solve():
	n = ii()
	a = li()
	b = li()
	inf = 1000000000.0
	dp = [inf for i in range(n)]
	ans = inf
	for i in range(1, n):
		for j in range(i):
			if a[j] < a[i]:
				dp[i] = min(dp[i], b[j] + b[i])
				if dp[j] != inf:
					ans = min(ans, dp[j] + b[i])
	if ans == inf:
		ans = -1
	print(ans)
solve()


import sys
import math
import os.path

def log(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

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

def nio(offset):
	return [int(x) + offset for x in input().split(' ')]

def nia():
	return list(map(int, input().split()))
CMAX = 1000000000
(n,) = ni()
s = nia()
c = nia()
l1 = [CMAX for _ in range(n)]
l2 = [CMAX for _ in range(n)]
for j in range(1, n):
	for i in range(j):
		if s[i] < s[j]:
			l1[j] = min(l1[j], c[i])
			l2[i] = min(l2[i], c[j])
res = CMAX
for i in range(n):
	res = min(res, l1[i] + l2[i] + c[i])
if res < CMAX:
	print(res)
else:
	print(-1)


from os import path
import sys, time, collections as c, math, pprint as p, itertools as it, operator as op
(maxx, localsys, mod) = (float('inf'), 0, int(1000000000.0 + 7))
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = maxx
for mid in range(1, n - 1):
	l = [maxx] + [c[i] for i in range(mid) if s[i] < s[mid]]
	r = [maxx] + [c[i] for i in range(mid + 1, n) if s[i] > s[mid]]
	ans = min(ans, min(l) + c[mid] + min(r))
print(ans if ans != float('inf') else -1)


n = int(input())
s = list(map(int, input().split()))
price = list(map(int, input().split()))
min_cost = float('inf')
for i in range(n):
	cost = price[i]
	price1 = float('inf')
	price2 = float('inf')
	for j in range(i):
		if s[j] < s[i]:
			price1 = min(price1, price[j])
	cost = cost + price1
	for j in range(i + 1, n):
		if s[j] > s[i]:
			price2 = min(price2, price[j])
	cost = cost + price2
	min_cost = min(cost, min_cost)
if min_cost == float('inf'):
	print(-1)
	exit()
print(min_cost)


import math

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

def getTransIntList(n):
	first = getIntList()
	m = len(first)
	result = [[0] * n for _ in range(m)]
	for i in range(m):
		result[i][0] = first[i]
	for j in range(1, n):
		curr = getIntList()
		for i in range(m):
			result[i][j] = curr[i]
	return result
n = int(input())
s = getIntList()
c = getIntList()
maxValue = 10 ** 8 + 1
result = maxValue * 3
minLeft = [0] * n
minRight = [0] * n
minLeft[0] = c[0]
for i in range(1, n):
	minLeft[i] = min(c[i], minLeft[i - 1])
minRight[n - 1] = c[n - 1]
for i in range(n - 2, -1, -1):
	minRight[i] = min(c[i], minRight[i + 1])
minSLeft = [0] * n
maxSRight = [0] * n
minSLeft[0] = s[0]
for i in range(1, n):
	minSLeft[i] = min(s[i], minSLeft[i - 1])
maxSRight[n - 1] = s[n - 1]
for i in range(n - 2, -1, -1):
	maxSRight[i] = max(s[i], maxSRight[i + 1])
prices = [(c[j], j) for j in range(1, n - 1)]
prices.sort()
for (currC, j) in prices:
	if minLeft[j - 1] + c[j] + minRight[j + 1] >= result:
		continue
	if minSLeft[j - 1] >= s[j] or s[j] >= maxSRight[j + 1]:
		continue
	a = maxValue
	for i in range(j):
		if s[i] < s[j]:
			a = min(a, c[i])
	b = maxValue
	for k in range(j + 1, n):
		if s[j] < s[k]:
			b = min(b, c[k])
	curr = a + b + c[j]
	result = min(result, curr)
if result == maxValue * 3:
	result = -1
print(result)


inf = 1234567890

class fenwick:

	def __init__(self, n):
		self.n = n
		self.f = [inf] * n

	def get(self, x):
		i = x
		ret = inf
		while i >= 0:
			ret = min(ret, self.f[i])
			i = (i & i + 1) - 1
		return ret

	def add(self, x, y):
		i = x
		while i < self.n:
			self.f[i] = min(self.f[i], y)
			i = i | i + 1
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
map_trick = {}
for x in s:
	map_trick[x] = 0
	map_trick[x - 1] = 0
m = 0
keys = sorted(list(map_trick.keys()))
for key in keys:
	map_trick[key] = m
	m += 1
a = list(zip(s, c))
ans = inf
fen = fenwick(8000)
for i in range(n):
	for j in range(i + 1, n):
		(size_first, cost_first) = a[i]
		(size_second, cost_second) = a[j]
		if size_first < size_second:
			ans = min(ans, cost_first + cost_second + fen.get(map_trick[size_first] - 1))
	fen.add(map_trick[size_first], cost_first)
print(ans if ans < inf else -1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
minimum = 100000000000.0
for j in range(1, n):
	temp = 10000000000.0
	ans = 0
	for i in range(0, j):
		if a[i] < a[j]:
			temp = min(temp, b[i])
	if temp == 0:
		continue
	ans += temp
	temp = 10000000000.0
	for k in range(j + 1, n):
		if a[k] > a[j]:
			temp = min(temp, b[k])
	if temp == 0:
		continue
	ans += temp
	ans += b[j]
	minimum = min(minimum, ans)
if minimum > 10000000000.0:
	print(-1)
else:
	print(minimum)


n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
ans = 4 * 10 ** 8
for j in range(1, n - 1):
	mini = 4 * 10 ** 8
	for i in range(0, j):
		if s[i] < s[j]:
			mini = min(mini, c[i])
	if mini == 4 * 10 ** 8:
		continue
	mink = 4 * 10 ** 8
	for k in range(j + 1, n):
		if s[j] < s[k]:
			mink = min(mink, c[k])
	if mink == 4 * 10 ** 8:
		continue
	ans = min(ans, mini + c[j] + mink)
if ans == 4 * 10 ** 8:
	print(-1)
else:
	print(ans)


R = lambda : list(map(int, input().split()))
I = 2 ** 29
n = int(input())
(s, c) = (R(), R())
r = min((c[j] + min([c[i] for i in range(j) if s[i] < s[j]], default=I) + min([c[i] for i in range(j + 1, n) if s[i] > s[j]], default=I) for j in range(n)))
print((r, -1)[r > I])


n = int(input())
ar = list(map(int, input().split()))
ar1 = list(map(int, input().split()))
ans3 = 10 ** 18
for i in range(n):
	ans1 = 10 ** 9 + 1
	ans2 = 10 ** 9 + 1
	for j in range(i - 1, -1, -1):
		if ar[i] > ar[j]:
			ans1 = min(ans1, ar1[j])
	for j in range(i + 1, n):
		if ar[i] < ar[j]:
			ans2 = min(ans2, ar1[j])
	if ans1 != 10 ** 9 + 1 and ans2 != 10 ** 9 + 1:
		ans3 = min(ans3, ans1 + ans2 + ar1[i])
if ans3 != 10 ** 18:
	print(ans3)
else:
	print(-1)


input()
h = list(map(int, input().split()))
s = list(map(int, input().split()))
sas = 1000000000.0
for j in range(len(h)):
	l = 1000000000.0
	for i in range(j):
		if h[i] < h[j]:
			l = min(l, s[i])
	r = 1000000000.0
	for k in range(j + 1, len(h)):
		if h[k] > h[j]:
			r = min(r, s[k])
	sas = min(sas, s[j] + l + r)
print(sas if sas != 1000000000.0 else -1)


class Display:

	def __init__(self, index, size, cost):
		self.index = index
		self.size = size
		self.cost = cost
		self.totalcost = cost
		self.next = None
		self.level = 0

def nextcycle(displays, level):
	for j in range(n):
		displays[j].next = None
		for k in range(j + 1, n):
			if displays[j].size < displays[k].size and displays[k].level == level:
				if displays[j].next == None or displays[k].totalcost < displays[j].next.totalcost:
					displays[j].next = displays[k]
		if displays[j].next != None:
			displays[j].totalcost = displays[j].cost + displays[j].next.totalcost
			displays[j].level = displays[j].next.level + 1
n = int(input())
sizes = input().split(' ')
costs = input().split(' ')
displays = []
i = 0
while i < n:
	displays.append(Display(i, int(sizes[i]), int(costs[i])))
	i += 1
for c in range(2):
	nextcycle(displays, c)
bestcost = float('inf')
for display in displays:
	if display.level == 2 and display.totalcost < bestcost:
		bestcost = display.totalcost
print(-1 if bestcost == float('inf') else bestcost)


def menorCustoEsq(s, c, size, custo):
	menor = None
	for i in range(0, len(s)):
		if menor == None and s[i] < size:
			menor = (s[i], c[i])
		elif s[i] < size:
			if menor[1] > c[i]:
				menor = (s[i], c[i])
	return menor

def menorCustoDir(s, c, size, custo):
	menor = None
	for i in range(0, len(s)):
		if menor == None and s[i] > size:
			menor = (s[i], c[i])
		elif s[i] > size:
			if menor[1] > c[i]:
				menor = (s[i], c[i])
	return menor
n = int(input())
sizes = [*map(int, input().split())]
costs = [*map(int, input().split())]
valores = []
for i in range(1, n - 1, 1):
	js = sizes[i]
	jc = costs[i]
	a = menorCustoEsq(sizes[:i], costs[:i], js, jc)
	k = menorCustoDir(sizes[i + 1:], costs[i + 1:], js, jc)
	if a != None and k != None:
		soma = a[1] + jc + k[1]
		valores.append(soma)
if len(valores) == 0:
	print(-1)
else:
	print(min(valores))


n = int(input())
a = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
ans = 10 ** 9 + 1
for j in range(1, n - 1):
	ans1 = 10 ** 9 + 1
	for i in range(j):
		if a[i] < a[j]:
			if ans1 > c[i]:
				ans1 = c[i]
	ans2 = 10 ** 9 + 1
	for k in range(j + 1, n):
		if a[j] < a[k]:
			if ans2 > c[k]:
				ans2 = c[k]
	ans = min(ans, ans1 + ans2 + c[j])
if ans == 10 ** 9 + 1:
	print(-1)
else:
	print(ans)


R = lambda : [int(i) for i in input().split()]
I = 3 * 10 ** 8
n = int(input())
(s, c) = (R(), R())
r = min((c[j] + min([I] + [c[i] for i in range(j) if s[i] < s[j]]) + min([I] + [c[i] for i in range(j + 1, n) if s[i] > s[j]]) for j in range(n)))
print((r, -1)[r > I])


R = lambda : [int(i) for i in input().split()]
I = 10 ** 9
n = int(input())
(s, c) = (R(), R())
r = I
for j in range(n):
	t1 = I
	for i in range(j):
		if s[i] < s[j]:
			t1 = min(t1, c[i])
	t2 = I
	for i in range(j + 1, n):
		if s[i] > s[j]:
			t2 = min(t2, c[i])
	r = min(c[j] + t1 + t2, r)
if r < I:
	print(r)
else:
	print('-1')


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = float('inf')
for i in range(1, n - 1):
	bef = aft = float('inf')
	for j in range(i):
		if a[j] < a[i]:
			bef = min(bef, b[j])
	for j in range(i, n):
		if a[i] < a[j]:
			aft = min(aft, b[j])
	ans = min(ans, b[i] + bef + aft)
print(-1 if ans > 10 ** 9 else ans)


class Display:

	def __init__(self, index, size, cost):
		self.index = index
		self.size = size
		self.cost = cost
		self.next = None
n = int(input())
sizes = input().split(' ')
costs = input().split(' ')
displays = []
i = 0
while i < n:
	displays.append(Display(i, int(sizes[i]), int(costs[i])))
	i += 1
for j in range(n):
	for k in range(j + 1, n):
		if displays[j].size < displays[k].size and (displays[j].next == None or displays[k].cost < displays[j].next.cost):
			displays[j].next = displays[k]
bestCost = float('inf')
for i in range(n):
	for j in range(i + 1, n):
		if displays[i].size < displays[j].size and displays[j].next != None:
			cost = displays[i].cost + displays[j].cost + displays[j].next.cost
			if cost < bestCost:
				bestCost = cost
print(-1 if bestCost == float('inf') else bestCost)


n = int(input())
S = [int(x) for x in input().split(' ')]
C = [int(x) for x in input().split(' ')]
bestCost = float('inf')
for i in range(len(S)):
	minLeft = float('inf')
	minRight = float('inf')
	for j in range(i):
		if S[j] < S[i] and C[j] < minLeft:
			minLeft = C[j]
	if minLeft == float('inf'):
		continue
	for j in range(i, len(S)):
		if S[j] > S[i] and C[j] < minRight:
			minRight = C[j]
	if minRight == float('inf'):
		continue
	if minLeft + minRight + C[i] < bestCost:
		bestCost = minLeft + minRight + C[i]
if bestCost == float('inf'):
	bestCost = -1
print(bestCost)


from math import inf
n = int(input())
a = [int(i) for i in input().split()]
val = [int(i) for i in input().split()]
dp = [[inf for i in range(n)] for j in range(3)]
for i in range(n):
	dp[0][i] = val[i]
	for j in range(i):
		if a[i] > a[j]:
			dp[1][i] = min(dp[1][i], dp[0][j] + val[i])
			dp[2][i] = min(dp[2][i], dp[1][j] + val[i])
m = inf
for i in range(n):
	m = min(m, dp[2][i])
if m == inf:
	print(-1)
else:
	print(m)


(n, s, c, v) = (int(input()), list(map(int, input().split())), list(map(int, input().split())), -1)
for i in range(1, n - 1):
	(k1, k2) = (-1, -1)
	for j in range(i):
		if s[j] < s[i] and (k1 == -1 or c[j] < c[k1]):
			k1 = j
	for j in range(i + 1, n):
		if s[j] > s[i] and (k2 == -1 or c[j] < c[k2]):
			k2 = j
	if k1 != -1 and k2 != -1:
		x = c[k1] + c[i] + c[k2]
		if v == -1 or x < v:
			v = c[k1] + c[i] + c[k2]
print(v)


import sys
from collections import deque
n = int(sys.stdin.readline().strip())
s = list(map(int, sys.stdin.readline().strip().split(' ')))
c = list(map(int, sys.stdin.readline().strip().split(' ')))
lower = [float('inf') for i in range(n)]
upper = [float('inf') for i in range(n)]
for i in range(n):
	for j in range(i):
		if s[i] > s[j]:
			lower[i] = min(lower[i], c[j])
for i in range(n - 1, -1, -1):
	for j in range(i + 1, n):
		if s[j] > s[i]:
			upper[i] = min(upper[i], c[j])
ans = float('inf')
for i in range(n):
	ans = min(ans, lower[i] + c[i] + upper[i])
print([-1, ans][ans != float('inf')])


class node:

	def __init__(self):
		self.id = 0
		self.c = 0
		self.s = 0
n = int(input())
p = [node() for i in range(n)]
for i in range(n):
	p[i].id = i
a = list(map(int, input().split()))
for i in range(n):
	p[i].s = a[i]
a = list(map(int, input().split()))
for i in range(n):
	p[i].c = a[i]
p.sort(key=lambda x: x.s)
ans = int(10000000000.0)
for i in range(1, n - 1):
	t1 = int(10000000000.0)
	t2 = int(10000000000.0)
	for j in range(i):
		if p[j].id < p[i].id and p[j].s < p[i].s:
			t1 = min(t1, p[j].c)
	for j in range(i + 1, n):
		if p[j].id > p[i].id and p[j].s > p[i].s:
			t2 = min(t2, p[j].c)
	ans = min(ans, t1 + t2 + p[i].c)
if ans == int(10000000000.0):
	print(-1)
else:
	print(ans)


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
	return int(stdin.readline().strip())

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

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

def solve():
	n = get_int()
	arr1 = get_list()
	arr2 = get_list()
	ans = float('inf')
	for i in range(n):
		mini = float('inf')
		for j in range(i):
			if arr1[j] < arr1[i]:
				mini = min(mini, arr2[j])
		maxi = float('inf')
		for k in range(i + 1, n):
			if arr1[k] > arr1[i]:
				maxi = min(maxi, arr2[k])
		ans = min(ans, arr2[i] + mini + maxi)
	if ans == float('inf'):
		ans = -1
	return ans

def main():
	print(solve())
TestCases = False
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
(a, b) = (1000000000000000.0, 1000000000000000.0)
ans = 1000000000000000.0
for i in range(1, n):
	(a, b) = (1000000000000000.0, 1000000000000000.0)
	for j in range(0, i):
		if s[i] > s[j]:
			a = min(a, c[j])
	for j in range(i + 1, n):
		if s[j] > s[i]:
			b = min(b, c[j])
	ans = min(ans, c[i] + a + b)
if ans == 1000000000000000.0:
	print(-1)
else:
	print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	(c, z) = ([0] * n, 10 ** 10)
	for i in range(n):
		mi = z
		for j in range(i + 1, n):
			if a[j] > a[i]:
				mi = min(mi, b[j])
		c[i] = mi + b[i]
	gmi = 10 ** 10
	for i in range(n):
		mi = z
		for j in range(i + 1, n):
			if a[j] > a[i]:
				mi = min(mi, c[j])
		gmi = min(gmi, mi + b[i])
	if gmi == z:
		print(-1)
	else:
		print(gmi)
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()


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
c1 = dict()
c2 = dict()
pmin = float('inf')
for i in range(n):
	tecs = s[i]
	tecpr = c[i]
	minpr = 10 ** 9 + 1
	for (k, v) in c2.items():
		if k < tecs:
			minpr = min(minpr, v)
	pmin = min(minpr + tecpr, pmin)
	minpr = 10 ** 9 + 1
	for (k, v) in c1.items():
		if k < tecs:
			minpr = min(minpr, v)
	if tecs not in c2:
		c2[tecs] = minpr + tecpr
	else:
		c2[tecs] = min(c2[tecs], minpr + tecpr)
	if s[i] not in c1:
		c1[tecs] = tecpr
	else:
		c1[tecs] = min(c1[tecs], tecpr)
if pmin > 10 ** 9:
	print(-1)
else:
	print(pmin)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

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

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

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

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

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

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
n = iinp()
arr = lmp()
cost = lmp()
(l1, l2, l3) = ([], [], [])
for i in range(n):
	for j in l1:
		if j[1] < arr[i]:
			ind = bl(l2, (j[0] + cost[i], arr[i]))
			l2.insert(ind, (j[0] + cost[i], arr[i]))
			break
	for j in l2:
		if j[1] < arr[i]:
			l3.append((j[0] + cost[i], arr[i]))
			break
	ind = bl(l1, (cost[i], arr[i]))
	l1.insert(ind, (cost[i], arr[i]))
l3.sort()
print(l3[0][0] if len(l3) else -1)


I = lambda : list(map(int, input().split()))
(n, s, a) = (int(input()), I(), I())
t = 3 * 10 ** 9
q = [0] * n
for i in range(n - 1, -1, -1):
	u = 10 ** 8
	for j in range(i - 1, -1, -1):
		if s[i] > s[j]:
			u = min(u, a[j])
	q[i] = u
for i in range(n):
	for j in range(i + 1, n):
		if s[i] < s[j]:
			t = min(t, a[i] + a[j] + q[i])
print(t if t <= sum(a) else -1)


import sys, os, io

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')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
INF = 99999999999999999999999999999999

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		n = ri()
		s = ria()
		c = ria()
		ans = INF
		for i in range(n):
			mid = s[i]
			mcl = INF
			mrl = INF
			for j in range(i - 1, -1, -1):
				if s[j] < mid:
					mcl = min(mcl, c[j])
			for j in range(i + 1, n):
				if s[j] > mid:
					mrl = min(mrl, c[j])
			ans = min(ans, c[i] + mcl + mrl)
		if ans == INF:
			wi(-1)
		else:
			wi(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


R = lambda : map(int, input().split())
I = 10 ** 10
n = int(input())
(s, c) = (list(R()), list(R()))
r = min((c[j] + min([I] + [c[i] for i in range(j) if s[i] < s[j]]) + min([I] + [c[i] for i in range(j + 1, n) if s[i] > s[j]]) for j in range(n)))
print((r, -1)[r > I])


from bisect import bisect
s = '5\n2 4 5 4 10\n40 30 20 10 40\n'
if False:

	def input(s=s.splitlines()):
		return s.pop(0)
n = int(input())
S = list(map(int, input().split()))
C = list(map(int, input().split()))
best = 10 ** 9

def one_size():
	best = [None] * n
	best[-1] = ([S[-1]], [C[-1]])
	(new_S, new_C) = best[-1]
	for i in range(n - 1)[::-1]:
		s = S[i]
		c = C[i]
		new_S = new_S[:]
		new_C = new_C[:]
		pos_s = bisect(new_S, s)
		pos_c = bisect(new_C, c)
		if pos_s >= pos_c:
			new_S[pos_c:pos_s] = [s]
			new_C[pos_c:pos_s] = [c]
		best[i] = (new_S, new_C)
	return best

def two_size(one_sizes):
	best = [None] * n
	best[-1] = [[], []]
	(new_S, new_C) = best[-1]
	for i in range(n - 1)[::-1]:
		s = S[i]
		c = C[i]
		new_S = new_S[:]
		new_C = new_C[:]
		pos = bisect(one_sizes[i + 1][0], s)
		if pos < len(one_sizes[i + 1][1]):
			c += one_sizes[i + 1][1][pos]
			pos_s = bisect(new_S, s)
			pos_c = bisect(new_C, c)
			if pos_s >= pos_c:
				new_S[pos_c:pos_s] = [s]
				new_C[pos_c:pos_s] = [c]
		best[i] = (new_S, new_C)
	return best
if n > 1000 or 1:
	result = two_size(two_size(one_size()))
	if result[0] and result[0][1]:
		print(result[0][1][0])
	else:
		print(-1)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
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 binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

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(int(n))
	return l

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

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ap = False
ans = 10000000000.0
for i in range(1, n - 1):
	ll = 10000000000.0
	for j in range(0, i):
		if s[j] < s[i]:
			ll = min(ll, c[j])
	rr = 10000000000.0
	for j in range(i + 1, n):
		if s[j] > s[i]:
			rr = min(rr, c[j])
	if ll != 10000000000.0 and rr != 10000000000.0:
		ap = True
		ans = min(ans, ll + rr + c[i])
if ap:
	print(ans)
else:
	print(-1)


import sys
inf = float('inf')
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
(mod, MOD) = (1000000007, 998244353)
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

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

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

def input():
	return sys.stdin.readline().strip()
n = int(input())
Arr = get_array()
cost = get_array()
flag = 0
min_total = inf
for i in range(1, n - 1):
	mini_i = cost[i]
	mini_j = inf
	mini_k = inf
	for j in range(i):
		if Arr[j] < Arr[i]:
			mini_j = min(mini_j, cost[j])
	for k in range(i + 1, n):
		if Arr[k] > Arr[i]:
			mini_k = min(mini_k, cost[k])
	if mini_i != inf and mini_j != inf and (mini_k != inf):
		flag = 1
		min_total = min(min_total, mini_i + mini_j + mini_k)
if flag == 0:
	print(-1)
else:
	print(min_total)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -1
for i in range(1, n - 1):
	temp1 = -1
	temp2 = -1
	for j in range(0, i):
		if s[i] > s[j]:
			if temp1 == -1:
				temp1 = c[j]
			else:
				temp1 = min(temp1, c[j])
	for j in range(i + 1, n):
		if s[i] < s[j]:
			if temp2 == -1:
				temp2 = c[j]
			else:
				temp2 = min(temp2, c[j])
	if ans != -1 and temp1 != -1 and (temp2 != -1):
		ans = min(ans, c[i] + temp1 + temp2)
	elif temp1 != -1 and temp2 != -1:
		ans = c[i] + temp1 + temp2
print(ans)


n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
f1 = [0 for x in range(0, 3005)]
f = [[99999999999 for x in range(0, 3005)] for i in range(1, 4)]
f.insert(0, f1)
for i in range(0, n):
	f[1][i] = c[i]
for x in range(2, 4):
	for i in range(x - 1, n):
		for j in range(0, i):
			if s[j] < s[i] and f[x - 1][j] != 99999999999:
				f[x][i] = min(f[x - 1][j] + c[i], f[x][i])
for i in range(1, n):
	f[3][i] = min(f[3][i - 1], f[3][i])
if f[x][i] != 99999999999:
	print(f[x][i])
else:
	print(-1)


n = int(input())
s = [int(x) for x in input().strip().split()]
c = [int(x) for x in input().strip().split()]
ans = float('inf')
for j in range(1, len(s) - 1):
	vi = float('inf')
	for i in range(j):
		if s[i] < s[j]:
			vi = min(vi, c[i])
	vk = float('inf')
	for k in range(j + 1, len(s)):
		if s[k] > s[j]:
			vk = min(vk, c[k])
	ans = min(ans, vi + vk + c[j])
print(ans if ans != float('inf') else -1)


n = int(input())
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
cn = 300000001
ext = 0
for i in range(1, n - 1):
	indj = s1[i]
	(vali, valk, valj) = (100000001, 100000001, s2[i])
	for j in range(0, i):
		if s1[j] < indj:
			if s2[j] < vali:
				vali = s2[j]
	for j in range(i + 1, n):
		if s1[j] > indj:
			if s2[j] < valk:
				valk = s2[j]
	if vali + valk + valj < cn:
		cn = vali + valk + valj
	if vali == 100000001 or valk == 100000001:
		ext += 1
if ext == n - 2:
	print(-1)
else:
	print(cn)


import bisect
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = 10 ** 18
for mid in range(1, n - 1):
	l1 = [c[i] for i in range(mid) if s[i] < s[mid]] + [10 ** 18]
	l2 = [c[i] for i in range(mid + 1, n) if s[i] > s[mid]] + [10 ** 18]
	ans = min(ans, min(l1) + c[mid] + min(l2))
if ans >= 10 ** 18:
	print(-1)
else:
	print(ans)


import sys
input = sys.stdin.readline
import math
a = int(input())
z = list(map(int, input().split()))
cost = list(map(int, input().split()))
minix = math.inf
for j in range(1, len(z) - 1):
	mini = math.inf
	for i in range(j):
		if z[i] < z[j]:
			if cost[i] < mini:
				mini = cost[i]
	mini3 = math.inf
	for k in range(j + 1, len(z)):
		if z[k] > z[j]:
			if mini3 > cost[k]:
				mini3 = cost[k]
	if mini3 + mini + cost[j] < minix:
		minix = mini3 + mini + cost[j]
if minix == math.inf:
	print(-1)
else:
	print(minix)


import os, 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 ceil
mod = 10 ** 9 + 7
for _ in range(1):
	n = int(input())
	font = list(map(int, input().split()))
	cost = list(map(int, input().split()))
	min_cost = float('inf')
	for j in range(1, n - 1):
		i = 0
		k = n - 1
		min_cost_from_left = float('inf')
		min_cost_from_right = float('inf')
		while i < j:
			if font[i] < font[j]:
				min_cost_from_left = min(min_cost_from_left, cost[i])
			i += 1
		while k > j:
			if font[k] > font[j]:
				min_cost_from_right = min(min_cost_from_right, cost[k])
			k -= 1
		if min_cost_from_left != float('inf') and min_cost_from_right != float('inf'):
			min_cost = min(min_cost, min_cost_from_left + cost[j] + min_cost_from_right)
	print(min_cost if min_cost != float('inf') else -1)


from collections import Counter
import string
import math
import sys
from fractions import Fraction

def array_int():
	return [int(i) for i in sys.stdin.readline().split()]

def vary(arrber_of_variables):
	if arrber_of_variables == 1:
		return int(sys.stdin.readline())
	if arrber_of_variables >= 2:
		return map(int, sys.stdin.readline().split())

def makedict(var):
	return dict(Counter(var))
testcases = 1
for _ in range(testcases):
	n = vary(1)
	indices = array_int()
	cost = array_int()
	ans = float('inf')
	mint = []
	for i in range(n):
		ans = float('inf')
		total = cost[i]
		flag = 0
		for j in range(i):
			if indices[i] > indices[j]:
				ans = min(ans, cost[j])
				flag = 1
		if flag != 0:
			total += ans
			ans = float('inf')
			flag = 0
			for k in range(i + 1, n):
				if indices[k] > indices[i]:
					ans = min(ans, cost[k])
					flag = 1
			if flag != 0:
				total += ans
				mint.append(total)
			else:
				continue
		else:
			continue
	if len(mint) > 0:
		print(min(mint))
	else:
		print(-1)


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

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

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

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_right(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		n = I()
		l = list(In())
		cost = list(In())
		ans = 10000000000.0
		for x in range(n):
			c1 = 10000000000.0
			c2 = 10000000000.0
			flag = 0
			for j in range(x):
				if l[j] < l[x]:
					flag += 1
					c1 = min(cost[j] + cost[x], c1)
			for j in range(x + 1, n):
				if l[x] < l[j]:
					flag += 1
					c2 = min(cost[j] + cost[x], c2)
			if flag >= 2:
				ans = min(c1 + c2 - cost[x], ans)
		if ans == 10000000000.0:
			print(-1)
		else:
			print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(1):
	main()


n = int(input())
size = list(map(int, input().split()))
cost = list(map(int, input().split()))
ans = 10 ** 9
for j in range(1, n):
	s_j = size[j]
	c_i = 10 ** 9
	for i in range(j):
		if size[j] > size[i]:
			c_i = min(c_i, cost[i])
	c_k = 10 ** 9
	for k in range(j + 1, n):
		if size[k] > size[j]:
			c_k = min(c_k, cost[k])
	x = cost[j] + c_i + c_k
	if x < ans:
		ans = x
if ans >= 10 ** 9:
	print(-1)
else:
	print(ans)


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
n = int(cin())
s = list(map(int, cin().split()))
c = list(map(int, cin().split()))
cost = 10 ** 12
for j in range(1, n - 1):
	(y, z) = (10 ** 15, 10 ** 15)
	m = 0
	for i in range(j):
		y = min(y, c[i]) * (s[j] > s[i]) + y * (s[j] <= s[i])
	for k in range(j + 1, n):
		z = min(z, c[k]) * (s[k] > s[j]) + z * (s[k] <= s[j])
	cost = min(cost, c[j] + y + z)
cout(str(cost * (cost < 10 ** 12) - 1 * (cost == 10 ** 12)))


from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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:
			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')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))

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

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

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (fast, lambda : map(int, z().split()))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer, end='\n'):
	stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
n = int(z())
arr1 = zzz()
arr2 = zzz()
ans = -1
for i in range(n):
	pv = float('inf')
	nx = float('inf')
	now = arr1[i]
	for j in range(i):
		if arr1[j] < now:
			pv = min(pv, arr2[j])
	for j in range(i + 1, n):
		if arr1[j] > now:
			nx = min(nx, arr2[j])
	if pv < float('inf') and nx < float('inf'):
		if ans == -1:
			ans = pv + nx + arr2[i]
		else:
			ans = min(ans, pv + nx + arr2[i])
print(ans)


R = lambda : map(int, input().split())
n = int(input())
arr = list(((f, c) for (f, c) in zip(R(), R())))
res = 1e+19
for i in range(1, n - 1):
	(lv, rv) = (1e+19, 1e+19)
	for j in range(i):
		lv = min(lv, arr[j][1] if arr[j][0] < arr[i][0] else 1e+19)
	for j in range(i + 1, n):
		rv = min(rv, arr[j][1] if arr[j][0] > arr[i][0] else 1e+19)
	res = min(res, lv + rv + arr[i][1])
print(res if res < 1e+19 else -1)


n = int(input())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))
ans = []
j = 1
while j < n - 1:
	m1 = m2 = 2000000000.0
	i = j - 1
	k = j + 1
	while i >= 0:
		if l[i] < l[j]:
			m1 = min(m1, l1[i])
		i -= 1
	while k < n:
		if l[k] > l[j]:
			m2 = min(m2, l1[k])
		k += 1
	x = m1 + m2 + l1[j]
	ans.append(x)
	j += 1
a = min(ans)
if a >= 2000000000.0:
	print(-1)
else:
	print(a)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = 10 ** 10
for j in range(1, n - 1):
	now_ans = c[j]
	money = 10 ** 10
	for i in range(j):
		if s[i] < s[j]:
			money = min(money, c[i])
	if money == 10 ** 10:
		pass
	now_ans += money
	money = 10 ** 10
	for i in range(j + 1, n):
		if s[i] > s[j]:
			money = min(money, c[i])
	if money == 10 ** 10:
		pass
	now_ans += money
	ans = min(ans, now_ans)
if ans == 10 ** 10:
	print(-1)
else:
	print(ans)


n = int(input())
l = list(map(int, input().split(' ')))
l2 = list(map(int, input().split(' ')))
dp_1 = l2.copy()
dp_2 = [9999999999] * n
dp_3 = [9999999999] * n
for i in range(1, n):
	for j in range(i):
		if l[i] > l[j]:
			dp_2[i] = min(dp_2[i], dp_1[j] + l2[i])
for i in range(1, n):
	for j in range(i):
		if l[i] > l[j]:
			dp_3[i] = min(dp_3[i], dp_2[j] + l2[i])
x = min(dp_3)
if x == 9999999999:
	print(-1)
else:
	print(x)


import sys
n = int(input())
li1 = []
li2 = []
li1 = list(map(int, input().split()))
li2 = list(map(int, input().split()))
a = 0
b = 0
min = sys.maxsize
for j in range(1, n - 1):
	min1 = sys.maxsize
	min2 = sys.maxsize
	for i in range(0, j):
		if li2[i] < min1 and li1[i] < li1[j]:
			min1 = li2[i]
			a = li1[i]
	for k in range(j + 1, n):
		if li2[k] < min2 and li1[k] > li1[j]:
			min2 = li2[k]
			b = li1[k]
	if min1 + li2[j] + min2 < min:
		min = min1 + li2[j] + min2
if a == 0 or b == 0:
	print('-1')
else:
	print(min)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
dp = [10000000000000000] * n
for i in range(1, n - 1):
	for j in range(i + 1, n):
		if s[j] > s[i]:
			dp[i] = min(dp[i], c[j] + c[i])
minm = 10000000000000000
for i in range(0, n - 2):
	for j in range(i + 1, n - 1):
		if s[j] > s[i]:
			minm = min(minm, dp[j] + c[i])
if minm == 10000000000000000:
	print(-1)
else:
	print(minm)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
l = 1e+19
for i in range(n - 1):
	m = r = 1e+19
	for j in range(i):
		if a[j] < a[i]:
			m = min(m, b[j])
	for j in range(i + 1, n):
		if a[j] > a[i]:
			r = min(r, b[j])
	l = min(l, b[i] + m + r)
if l == 1e+19:
	print(-1)
else:
	print(l)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
dp2 = [float('inf') for i in range(n)]
dp3 = [float('inf') for i in range(n)]
for i in range(1, n):
	j = i - 1
	while j >= 0:
		if s[j] < s[i]:
			dp2[i] = min(c[i] + c[j], dp2[i])
		j -= 1
ans = float('inf')
for i in range(2, n):
	j = i - 1
	while j >= 0:
		if s[j] < s[i]:
			dp3[i] = min(dp3[i], c[i] + dp2[j])
			ans = min(ans, dp3[i])
		j -= 1
print(ans if ans != float('inf') else -1)


from sys import stdin
n = int(stdin.readline())
size = list(map(int, stdin.readline().split()))
price = list(map(int, stdin.readline().split()))
temp = [3 * 10 ** 8 + 1] * n
ans = [3 * 10 ** 8 + 1] * n
for i in range(n):
	for j in range(i + 1, n):
		if size[i] >= size[j]:
			continue
		temp[j] = min(temp[j], price[i] + price[j])
for i in range(n):
	for j in range(i + 1, n):
		if size[i] >= size[j]:
			continue
		ans[j] = min(ans[j], temp[i] + price[j])
res = 3 * 10 ** 8 + 1
for i in range(n):
	if res > ans[i]:
		res = ans[i]
if res == 3 * 10 ** 8 + 1:
	print('-1')
else:
	print(res)


n = int(input())
arr = [int(w) for w in input().split(' ')]
c = [int(w) for w in input().split(' ')]
inf = 10 ** 18
dp = [[inf for x in range(n)] for x in range(3)]
dp[0] = c.copy()
for i in range(1, 3):
	for j in range(i, n):
		for k in range(j):
			if arr[j] > arr[k]:
				dp[i][j] = min(c[j] + dp[i - 1][k], dp[i][j])
ans = min(dp[-1])
if ans == inf:
	ans = -1
print(ans)


def answer(n, A, B):
	dp = [[float('inf') for i in range(n)] for j in range(3)]
	dp[0][0] = B[0]
	for i in range(3):
		for j in range(1, n):
			if i == 0:
				dp[i][j] = B[j]
			else:
				for k in range(j):
					if A[j] > A[k]:
						dp[i][j] = min(dp[i][j], dp[i - 1][k] + B[j])
	mini = min(dp[2])
	if mini == float('inf'):
		return -1
	return mini
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print(answer(n, A, B))


n = int(input())
arr = list(map(int, input().split()))
cost = list(map(int, input().split()))
ans = 10 ** 10
for i in range(1, n - 1):
	cur = arr[i]
	(l, r) = (10 ** 10, 10 ** 10)
	for j in range(i - 1, -1, -1):
		if arr[j] < cur:
			l = min(l, cost[j])
	for j in range(i + 1, n):
		if arr[j] > cur:
			r = min(r, cost[j])
	ans = min(ans, cost[i] + l + r)
if ans == 10 ** 10:
	print(-1)
else:
	print(ans)


class SegTree:

	def __init__(self, init_val, ide_ele, segfunc):
		self.n = len(init_val)
		self.num = 2 ** (self.n - 1).bit_length()
		self.ide_ele = ide_ele
		self.segfunc = segfunc
		self.seg = [ide_ele] * 2 * self.num
		for i in range(self.n):
			self.seg[i + self.num] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.seg[i] = self.segfunc(self.seg[2 * i], self.seg[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.seg[k] = x
		while k:
			k = k >> 1
			self.seg[k] = self.segfunc(self.seg[2 * k], self.seg[2 * k + 1])

	def query(self, l, r):
		if r <= l:
			return self.ide_ele
		l += self.num
		r += self.num
		lres = self.ide_ele
		rres = self.ide_ele
		while l < r:
			if r & 1:
				r -= 1
				rres = self.segfunc(self.seg[r], rres)
			if l & 1:
				lres = self.segfunc(lres, self.seg[l])
				l += 1
			l = l >> 1
			r = r >> 1
		res = self.segfunc(lres, rres)
		return res

	def __str__(self):
		arr = [self.query(i, i + 1) for i in range(self.n)]
		return str(arr)
n = int(input())
S = list(map(int, input().split()))
C = list(map(int, input().split()))
SA = list(set(S))
SA = sorted(SA)
d = {}
for (i, s) in enumerate(SA):
	d[s] = i
S = [d[s] for s in S]
L = [0] * n
R = [0] * n
INF = 10 ** 18
N = len(d)
seg = SegTree([INF] * (N + 1), INF, min)
seg.update(S[0], C[0])
for i in range(1, n - 1):
	s = S[i]
	L[i] = seg.query(0, s)
	seg.update(s, C[i])
seg = SegTree([INF] * (N + 1), INF, min)
seg.update(S[-1], C[-1])
for i in reversed(range(1, n - 1)):
	s = S[i]
	R[i] = seg.query(s + 1, seg.n)
	seg.update(s, C[i])
ans = INF
for i in range(1, n - 1):
	ans = min(ans, L[i] + C[i] + R[i])
if ans >= INF:
	print(-1)
else:
	print(ans)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
MIN = 3 * 10 ** 8 + 1
dp = [MIN] * n
for i in range(1, len(s)):
	for j in range(0, i):
		if s[j] < s[i]:
			dp[i] = min(dp[i], c[j] + c[i])
			MIN = min(dp[j] + c[i], MIN)
if MIN > 3 * 10 ** 8:
	print(-1)
else:
	print(MIN)


n = int(input())
s = input()
S = list(map(int, list(s.split())))
c = input()
C = list(map(int, list(c.split())))
table = [[10 ** 9 for i in range(4)] for i in range(n)]
for i in range(n):
	table[i][1] = C[i]
for i in range(2, 4):
	for j in range(i - 1, n):
		for k in range(j):
			if S[k] < S[j]:
				table[j][i] = min(table[k][i - 1] + C[j], table[j][i])
m = 10 ** 9
for i in range(n):
	m = min(table[i][3], m)
if m == 10 ** 9:
	print(-1)
else:
	print(m)


n = int(input())
ss = list(map(int, input().split()))
cc = list(map(int, input().split()))
d1 = {}
d2 = {}
d3 = {}
for i in range(n):
	s = ss[i]
	c = cc[i]
	if s in d1.keys():
		d1[s] = min(d1[s], c)
	else:
		d1[s] = c
	m = 10000000001
	for d in d1.keys():
		if d < s and d1[d] < m:
			m = d1[d]
	if s in d2.keys():
		d2[s] = min(d2[s], m + c)
	else:
		d2[s] = m + c
	m = 10000000001
	for d in d2.keys():
		if d < s and d2[d] < m:
			m = d2[d]
	if s in d3.keys():
		d3[s] = min(d3[s], m + c)
	else:
		d3[s] = m + c
m = 10000000001
for d in d3.keys():
	if d3[d] < m:
		m = d3[d]
if m < 10000000001:
	print(m)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
sumi = []
for i in range(1, len(a) - 1):
	s = 10000000000
	l = 10000000000
	for j in range(i):
		if a[j] < a[i]:
			k = b[i] + b[j]
			if s > k:
				s = k
	for j in range(i + 1, len(a)):
		if a[j] > a[i]:
			k = b[i] + b[j]
			if l > k:
				l = k
	sumi.append(s + l - b[i])
if min(sumi) >= 10000000000:
	print(-1)
else:
	print(min(sumi))


n = int(input())
font = list(map(int, input().split()))
cost = list(map(int, input().split()))
costList = [[[], []] for _ in range(n)]
limit = 10 ** 9
ans = limit
for i in range(n - 1):
	mysize = font[i]
	for j in range(i + 1, n):
		if mysize < font[j]:
			costList[i][0].append(j)
			if len(costList[i][1]) == 0:
				costList[i][1].append(cost[j])
			else:
				costList[i][1] = [min(cost[j], costList[i][1][0])]
for i in range(n - 2):
	cur = cost[i]
	for idex in costList[i][0]:
		next = cur + cost[idex]
		if len(costList[idex][1]) > 0:
			ans = min(ans, next + costList[idex][1][0])
print(ans if ans != limit else -1)


import sys
imput = sys.stdin.readline

class SegmentTree:

	def __init__(self, n):
		self.n = n
		self.INF = 2 ** 31 - 1
		self.size = 1
		while self.size < n:
			self.size *= 2
		self.node = [self.INF] * (2 * self.size - 1)

	def update(self, i, val):
		i += self.size - 1
		self.node[i] = val
		while i > 0:
			i = (i - 1) // 2
			self.node[i] = min(self.node[2 * i + 1], self.node[2 * i + 2])

	def get_min(self, begin, end):
		begin += self.size - 1
		end += self.size - 1
		s = self.INF
		while begin < end:
			if end - 1 & 1:
				end -= 1
				s = min(s, self.node[end])
			if begin - 1 & 1:
				s = min(s, self.node[begin])
				begin += 1
			begin = (begin - 1) // 2
			end = (end - 1) // 2
		return s

def compress(array):
	array2 = sorted(set(array))
	memo = {value: index for (index, value) in enumerate(array2)}
	for i in range(len(array)):
		array[i] = memo[array[i]]
	return array
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
st = SegmentTree(n)
a = compress(a)
ans = [0] * n
for i in range(n):
	ans[i] = st.get_min(0, a[i])
	st.update(a[i], min(b[i], st.get_min(a[i], a[i] + 1)))
st = SegmentTree(n)
for i in range(n)[::-1]:
	ans[i] += st.get_min(a[i] + 1, n)
	st.update(a[i], min(b[i], st.get_min(a[i], a[i] + 1)))
for i in range(n):
	ans[i] += b[i]
min_ans = min(ans)
if min_ans < 2 ** 31 - 1:
	print(min_ans)
else:
	print(-1)


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

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

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
inf = 1e+18
n = inn()
a = arr()
val = arr()
ans = inf
for i in range(n):
	ans1 = inf
	ans2 = inf
	for j in range(i):
		if a[j] < a[i]:
			ans1 = min(ans1, val[i] + val[j])
	for j in range(i + 1, n):
		if a[j] > a[i]:
			ans2 = min(ans2, ans1 + val[j])
	ans = min(ans, ans2)
if ans == inf:
	print(-1)
else:
	print(ans)


from sys import stdin, stdout
inf = 3000000000.0
n = int(input())
s = [int(x) for x in input().strip().split(' ')]
c = [int(x) for x in input().strip().split(' ')]
dp1 = [inf for x in s]
dp2 = [inf for x in s]
for i in range(1, n - 1):
	for j in range(0, i):
		if s[j] < s[i]:
			dp1[i] = min(dp1[i], c[j])
for i in range(1, n - 1):
	for j in range(i + 1, n):
		if s[j] > s[i]:
			dp2[i] = min(dp2[i], c[j])
ans = 3000000000.0
for i in range(1, n - 1):
	ans = min(ans, c[i] + dp1[i] + dp2[i])
if ans >= 3000000000.0:
	print('-1')
else:
	print(ans)


import sys, math
input = sys.stdin.readline
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
cost = math.inf
for j in range(1, n - 1):
	mini = math.inf
	maxi = math.inf
	for i in range(j):
		if s[i] < s[j]:
			mini = min(mini, c[i])
	for k in range(j + 1, n):
		if s[k] > s[j]:
			maxi = min(maxi, c[k])
	cost = min(cost, mini + maxi + c[j])
if cost == math.inf:
	print(-1)
else:
	print(cost)


import sys
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
minTwoCost = [-1] * n
for i in range(1, n):
	x = sys.maxsize
	found = False
	for j in range(i):
		if s[j] < s[i]:
			x = min(x, c[j])
			found = True
	if found:
		minTwoCost[i] = c[i] + x
answer = sys.maxsize
found = False
for i in range(2, n):
	for j in range(i - 1, -1, -1):
		if minTwoCost[j] >= 0 and s[i] > s[j]:
			answer = min(answer, c[i] + minTwoCost[j])
			found = True
if found:
	print(answer)
else:
	print(-1)


inp = lambda : map(int, input().rstrip().split())
n = int(input())
s = list(inp())
c = list(inp())
dp = [100000000000] * n
for i in range(1, n - 1):
	for j in range(i + 1, n):
		if s[j] > s[i]:
			dp[i] = min(dp[i], c[j] + c[i])
minm = 100000000000
for i in range(0, n - 2):
	for j in range(i + 1, n - 1):
		if s[j] > s[i]:
			minm = min(minm, dp[j] + c[i])
if minm == 100000000000:
	print(-1)
else:
	print(minm)


import sys
from math import *

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())
n = mint()
s = list(mints())
c = list(mints())
r = 1000000000.0
for j in range(n):
	x = s[j]
	i = 1000000000.0
	for p in range(j):
		if s[p] < x and c[p] < i:
			i = c[p]
	k = 1000000000.0
	for p in range(j + 1, n):
		if s[p] > x and c[p] < k:
			k = c[p]
	r = min(r, i + c[j] + k)
if r >= 1000000000.0:
	print(-1)
else:
	print(r)


n = int(input())
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
m = 999999999
for i in range(1, n - 1):
	m1 = 999999999
	m2 = 999999999
	ind1 = -1
	ind2 = -1
	for j in range(i):
		if a[j] < a[i]:
			if c[j] < m1:
				m1 = c[j]
				ind1 = j
	for j in range(i + 1, n):
		if a[i] < a[j]:
			if c[j] < m2:
				m2 = c[j]
				ind2 = j
	if ind1 != -1 and ind2 != -1:
		m = min(m, c[ind1] + c[i] + c[ind2])
if m != 999999999:
	print(m)
else:
	print(-1)


n = int(input())
size = [int(x) for x in input().split()]
costs = [int(x) for x in input().split()]
dp = [10000000000 for _ in range(n)]
best = 1000000000
for i in range(n):
	for k in range(0, i):
		if size[k] < size[i]:
			dp[i] = min(dp[i], costs[k] + costs[i])
			best = min(dp[k] + costs[i], best)
if best == 1000000000:
	print(-1)
else:
	print(best)


import sys
input = sys.stdin.readline
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
dp = c
for _ in range(2):
	dp2 = []
	for i in range(n):
		t = 10 ** 9
		for j in range(i):
			if t > dp[j] and s[j] < s[i]:
				t = dp[j]
		dp2.append(t + c[i])
	dp = dp2
ans = min(dp)
if ans >= 10 ** 9:
	ans = -1
print(ans)


from operator import __gt__, __lt__

def helper(op):
	xx = list(map(float, input().split()))
	(le, ri, a) = ([], [], xx[0])
	for b in xx:
		if a > b:
			a = b
		le.append(a)
	for a in reversed(xx):
		if op(b, a):
			b = a
		ri.append(b)
	ri.reverse()
	return (xx, le, ri)
(n, res) = (int(input()), 9000000000.0)
(ss, sLe, sRi) = helper(__lt__)
(cc, cLe, cRi) = helper(__gt__)
for j in sorted(range(1, n - 1), key=cc.__getitem__):
	(s, c) = (ss[j], cc[j])
	if cLe[j - 1] + c + cRi[j + 1] < res and sLe[j - 1] < s < sRi[j + 1]:
		a = b = 9000000000.0
		for i in range(j):
			if ss[i] < s and a > cc[i]:
				a = cc[i]
		for k in range(j + 1, n):
			if s < ss[k] and b > cc[k]:
				b = cc[k]
		if res > a + b + c:
			res = a + b + c
print(int(res) if res < 9000000000.0 else -1)


n = int(input())
lis = list(map(int, input().split()))
cos = list(map(int, input().split()))
ans = a = b = c = 100000000000000000
for j in range(1, n - 1):
	a = b = 100000000000000000
	for i in range(j):
		if lis[i] < lis[j]:
			a = min(a, cos[i])
	for k in range(j + 1, n):
		if lis[j] < lis[k]:
			b = min(b, cos[k])
	ans = min(ans, a + b + cos[j])
if ans == c:
	print(-1)
else:
	print(ans)


import sys

def inpt():
	return sys.stdin.readline().strip()
n = int(inpt())
s = [int(i) for i in inpt().split()]
c = [int(i) for i in inpt().split()]
mi = 9999999999
for i in range(1, n - 1):
	m1 = 9999999999
	for j in range(i):
		if s[j] < s[i]:
			m1 = min(m1, c[j])
	m2 = 9999999999
	for k in range(i + 1, n):
		if s[i] < s[k]:
			m2 = min(m2, c[k])
	mi = min(mi, m1 + c[i] + m2)
if mi == 9999999999:
	print(-1)
else:
	print(mi)


def main():
	(n, inf, res) = (int(input()), 9000000000.0, [])
	ss = list(map(float, input().split()))
	cc = list(map(float, input().split()))
	tmp = [(ss[0], cc[0])]
	for (s, c) in zip(ss[1:-1], cc[1:-1]):
		res.append(min((b for (a, b) in tmp if a < s), default=inf) + c)
		tmp.append((s, c))
	res.reverse()
	tmp = [(ss[-1], cc[-1])]
	for (i, s, c) in zip(range(n), ss[-2:0:-1], cc[-2:0:-1]):
		res[i] += min((b for (a, b) in tmp if a > s), default=inf)
		tmp.append((s, c))
	r = min(res)
	print(int(r) if r < inf else -1)
main()


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = (10 ** 9 + 1) * 3
m = 10 ** 9 + 1
m1 = 10 ** 9 + 1
t = 0
for i in range(0, n):
	m = 10 ** 9 + 1
	m1 = 10 ** 9 + 1
	su = b[i]
	for j in range(0, i):
		if a[j] < a[i]:
			m = min(m, b[j])
	for j in range(i + 1, n):
		if a[j] > a[i]:
			m1 = min(m1, b[j])
	if m != 10 ** 9 + 1 and m1 != 10 ** 9 + 1:
		t = 1
	ans = min(ans, su + m + m1)
if t == 1:
	print(ans)
else:
	print(-1)


import math as mt
import sys, string, bisect
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
d = defaultdict(int)
n = I()
l = L()
c = L()
ans = 10 ** 10
f = 1
for i in range(1, n - 1):
	sj = l[i]
	le = 0
	r = 0
	left = 10 ** 10
	right = 10 ** 10
	for j in range(i):
		if l[j] < l[i]:
			le = 1
			left = min(left, c[j])
	for j in range(i + 1, n):
		if l[j] > l[i]:
			r = 1
			right = min(right, c[j])
	if le * r:
		f = 0
		ans = min(ans, left + right + c[i])
if f == 1:
	print(-1)
else:
	print(ans)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
m = float('inf')
for j in range(1, n - 1):
	x = float('inf')
	y = float('inf')
	for i in range(j):
		if s[i] < s[j]:
			x = min(x, c[i])
	for k in range(j + 1, n):
		if s[j] < s[k]:
			y = min(y, c[k])
	m = min(m, x + y + c[j])
if m == float('inf'):
	m = -1
print(m)


n = int(input())
s = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
dp = [[float('inf') for _ in range(4)] for _ in range(n)]
for i in range(n):
	dp[i][1] = c[i]
for i in range(n):
	for j in range(1, 4):
		for r in range(i):
			if s[r] < s[i]:
				dp[i][j] = min(dp[i][j], c[i] + dp[r][j - 1])
ans = min((i[3] for i in dp))
if ans == float('inf'):
	ans = -1
print(ans)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ans = 10 ** 18
	for i in range(n - 1):
		l = r = 10 ** 18
		for j in range(i):
			if a[j] < a[i]:
				l = min(l, b[j])
		for j in range(i + 1, n):
			if a[j] > a[i]:
				r = min(r, b[j])
		ans = min(ans, b[i] + l + r)
	if ans == 10 ** 18:
		print('-1')
	else:
		print(ans)
main()


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
res = 1000000000
for j in range(1, n - 1):
	(x, y) = (s[j], c[j])
	mn = 1000000000
	res1 = y
	for i in range(j):
		if s[i] < x:
			if mn > c[i]:
				mn = c[i]
	res1 += mn
	mn = 1000000000
	for k in range(j + 1, n):
		if x < s[k]:
			if mn > c[k]:
				mn = c[k]
	res1 += mn
	res = min(res, res1)
if res == 1000000000:
	print(-1)
else:
	print(res)


n = int(input())
m = list(map(int, input().split()))
c = list(map(int, input().split()))
import math
d = math.inf
for i in range(1, n - 1):
	a = math.inf
	h = math.inf
	for j in range(i):
		if m[i] > m[j]:
			h = min(c[i] + c[j], h)
	for k in range(i + 1, n):
		if m[k] > m[i]:
			a = min(c[i] + c[k], a)
	d = min(a + h - c[i], d)
if d == math.inf:
	print(-1)
else:
	print(d)


n = int(input())
S = [int(x) for x in input().split(' ')]
C = [int(x) for x in input().split(' ')]
dp = [float('inf')] * n
ans = float('inf')
for i in range(n):
	for j in range(i + 1, n):
		if S[j] > S[i] and C[j] < dp[i]:
			dp[i] = C[j]
for i in range(n):
	for j in range(i + 1, n):
		if S[j] > S[i]:
			ans = min(ans, C[i] + C[j] + dp[j])
if ans == float('inf'):
	ans = -1
print(ans)


n = int(input())
l = list(map(int, input().split()))
v = list(map(int, input().split()))
d = dict()
for i in range(n):
	take = []
	for j in range(i + 1, n):
		if l[i] < l[j]:
			take.append(v[j])
	d[i] = sorted(take)
mini = 99999999999
for i in range(n):
	sum1 = v[i]
	for j in range(i + 1, n):
		if l[i] < l[j]:
			sum1 = v[j] + v[i]
			if len(d[j]) != 0:
				sum1 = v[i] + v[j] + d[j][0]
				if mini > sum1:
					mini = sum1
if mini == 99999999999:
	print('-1')
else:
	print(mini)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
n = ii1()
font = iia()
cost = iia()
res = float('inf')
for i in range(1, n):
	left = float('inf')
	for j in range(i):
		if font[j] < font[i]:
			left = min(left, cost[i] + cost[j])
	if left != float('inf'):
		for j in range(i + 1, n):
			if font[j] > font[i]:
				res = min(res, left + cost[j])
if res == float('inf'):
	print(-1)
else:
	print(res)


import sys
n = int(input().strip())
sizes = list(map(int, input().strip().split()))
cost = list(map(int, input().strip().split()))
tot = []
for i in range(n):
	tot.append([sizes[i], cost[i]])
ret = False
lcomp = []
for j in range(len(tot)):
	if j > 0 and j < len(tot) - 1:
		temp1 = tot[:j]
		temp2 = tot[j + 1:]
		mi_1 = sys.maxsize
		ret1 = False
		for i in range(len(temp1)):
			if temp1[i][0] < tot[j][0]:
				mi_1 = min(mi_1, temp1[i][1])
				ret1 = True
		mi_2 = sys.maxsize
		ret2 = False
		for k in range(len(temp2)):
			if temp2[k][0] > tot[j][0]:
				mi_2 = min(mi_2, temp2[k][1])
				ret2 = True
		if ret1 and ret2:
			ret = True
			lcomp.append(mi_1 + tot[j][1] + mi_2)
if ret:
	print(min(lcomp))
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
MAXANS = 300000010
f = {1: [c[i] for i in range(n)], 2: [MAXANS for _ in range(n)], 3: [MAXANS for _ in range(n)]}
v = [False for _ in range(n)]
l = 2
for i in range(n - 1):
	if v[i]:
		continue
	for j in range(i + 1, n):
		if a[j] > a[i] and c[j] > c[i]:
			v[j] = True
		if a[i] < a[j] and f[l - 1][i] + c[j] < f[l][j]:
			f[l][j] = f[l - 1][i] + c[j]
l = 3
for i in range(n - 1):
	if f[2][i] == MAXANS:
		continue
	for j in range(i + 1, n):
		if a[i] < a[j] and f[l - 1][i] + c[j] < f[l][j]:
			f[l][j] = f[l - 1][i] + c[j]
ans = min(f[3])
if ans == MAXANS:
	print(-1)
else:
	print(ans)


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

def read_int():
	return int(input())

def solve():
	n = read_int()
	a = read_line()
	b = read_line()
	res = 1e+18
	for j in range(n):
		cost = [1e+18, 1e+18]
		for i in range(0, j):
			if a[i] < a[j]:
				cost[0] = min(cost[0], b[i])
		for k in range(j, n):
			if a[j] < a[k]:
				cost[1] = min(cost[1], b[k])
		res = min(res, cost[0] + cost[1] + b[j])
	print(res if res != 1e+18 else -1)
t = 1
while t > 0:
	solve()
	t -= 1


import sys
input = sys.stdin.readline
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
d = {}
for i in range(n - 1):
	ans = 10 ** 12
	for j in range(i + 1, n):
		if s[i] < s[j]:
			ans = min(ans, c[i] + c[j])
	d[i] = ans
ans = 10 ** 12
for i in range(n - 2):
	for j in range(i + 1, n - 1):
		if s[i] < s[j]:
			ans = min(ans, c[i] + d[j])
if ans == 10 ** 12:
	print(-1)
else:
	print(ans)


TN = 1

def solution():
	n = int(input())
	s = list(map(int, input().split()))
	c = list(map(int, input().split()))
	ans = 3 * 10 ** 9 + 2
	for j in range(1, n - 1):
		ans_i = c[j]
		cur_i = 10 ** 9 + 2
		cur_k = 10 ** 9 + 2
		for i in range(j):
			if s[i] < s[j] and cur_i > c[i]:
				cur_i = c[i]
		for k in range(j + 1, n):
			if s[j] < s[k] and cur_k > c[k]:
				cur_k = c[k]
		if cur_i == 10 ** 9 + 2:
			ans_i = 3 * 10 ** 9 + 2
		elif cur_k == 10 ** 9 + 2:
			ans_i = 3 * 10 ** 9 + 2
		else:
			ans_i += cur_i + cur_k
		if ans > ans_i:
			ans = ans_i
	if ans == 3 * 10 ** 9 + 2:
		ans = -1
	print(ans)
while TN != 0:
	solution()
	TN -= 1


from sys import stdin
a = int(stdin.readline())
A = list(map(int, stdin.readline().split()))
B = list(map(int, stdin.readline().split()))
SOL = 10 ** 9
UU = 0
for t in range(1, a - 1):
	MIN = 10 ** 8 + 1
	K = 0
	for u in range(0, t):
		if A[u] < A[t]:
			K = 1
			MIN = min(MIN, B[u])
	if K == 0:
		continue
	ans = int(B[t]) + MIN
	MIN = 10 ** 8 + 1
	K = 0
	for y in range(t + 1, a):
		if A[y] > A[t]:
			MIN = min(MIN, B[y])
			K = 1
	ans += MIN
	if K == 1:
		SOL = min(SOL, ans)
		UU = 1
if UU == 1:
	print(SOL)
else:
	print(-1)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
x = [0]
for i in range(1, n):
	t = 0
	for j in range(i + 1, n):
		if s[j] > s[i]:
			if t == 0:
				t = c[j]
			else:
				t = min(t, c[j])
	x.append(t)
ans = -1
for i in range(n):
	t = 0
	for j in range(i + 1, n):
		if s[j] > s[i] and x[j] != 0:
			if ans == -1:
				ans = c[j] + x[j] + c[i]
			else:
				ans = min(ans, c[j] + x[j] + c[i])
print(ans)


import sys
n = int(input())
l = list(map(int, input().split()))
c = list(map(int, input().split()))
a = []
for i in range(1, n - 1):
	lr = sys.maxsize
	lc = sys.maxsize
	for j in range(0, i):
		if l[i] > l[j]:
			lc = min(lc, c[j])
	for j in range(i + 1, n):
		if l[j] > l[i]:
			lr = min(lr, c[j])
	if lr < sys.maxsize and lc < sys.maxsize:
		a.append(lr + lc + c[i])
if not a:
	print(-1)
else:
	print(min(a))


def f(n, S, C):
	total = -1
	for i in range(1, n - 1):
		l = 10 ** 8 + 100
		for m in range(i - 1, -1, -1):
			if S[m] < S[i]:
				l = min(l, C[m])
		r = 10 ** 8 + 100
		for o in range(i + 1, n):
			if S[o] > S[i]:
				r = min(r, C[o])
		if l == 10 ** 8 + 100 or r == 10 ** 8 + 100:
			continue
		elif total != -1:
			total = min(total, C[i] + r + l)
		else:
			total = C[i] + r + l
	return total
n = int(input())
S = [int(a) for a in input().split()]
C = [int(b) for b in input().split()]
print(f(n, S, C))


def solve(n, s, c):
	INF = float('inf')
	ans = INF
	for i in range(n):
		first = INF
		for j in range(i):
			if s[j] < s[i]:
				first = min(first, c[j])
		if first == INF:
			continue
		second = INF
		for j in range(i + 1, n):
			if s[i] < s[j]:
				second = min(second, c[j])
		if second == INF:
			continue
		ans = min(ans, first + c[i] + second)
	ans = -1 if ans == INF else ans
	print(ans)
n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
solve(n, s, c)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
dp = [float('inf')] * n
for i in range(1, n):
	mn = float('inf')
	for j in range(i):
		if s[i] > s[j]:
			mn = min(mn, c[i] + c[j])
	dp[i] = mn
res = float('inf')
for i in range(1, n):
	for j in range(i):
		if s[i] > s[j]:
			res = min(res, c[i] + dp[j])
if res == float('inf'):
	res = -1
print(res)


import sys
import operator
inf = float('inf')
mod = 1000000007

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

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

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

def main():
	n = int(input())
	size = get_array()
	cost = get_array()
	dp = [inf for _ in range(n)]
	for i in range(n):
		for j in range(i + 1, n):
			if size[j] > size[i]:
				dp[i] = min(dp[i], cost[j])
	ans = inf
	for i in range(n):
		for j in range(i + 1, n):
			if size[j] > size[i]:
				ans = min(ans, dp[j] + cost[i] + cost[j])
	print(ans) if ans != inf else print(-1)
main()


n = int(input())
s = list(map(int, input().strip().split()))
c = list(map(int, input().strip().split()))
dp = [float('inf') for i in range(n)]
for i in range(n):
	for j in range(i):
		if s[j] < s[i]:
			dp[i] = min(dp[i], c[i] + c[j])
dp2 = [float('inf') for i in range(n)]
for i in range(n):
	for j in range(i):
		if s[j] < s[i]:
			dp2[i] = min(dp2[i], dp[j] + c[i])
ans = min(dp2)
if ans == float('inf'):
	print(-1)
else:
	print(ans)


mod = 1000000007
MOD = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
it = lambda : tuple(map(int, input().split()))
ls = lambda : list(input())
n = ii()
l = il()
c = il()
mn = 10 ** 20
for i in range(1, n - 1):
	lmn1 = [c[j] for j in range(i) if l[j] < l[i]]
	lmn2 = [c[j] for j in range(i + 1, n) if l[j] > l[i]]
	if len(lmn1) and len(lmn2):
		mn = min(mn, min(lmn1) + min(lmn2) + c[i])
print(mn if mn != 10 ** 20 else -1)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ck_min = []
for i in range(n):
	ck_min_i = 10 ** 18
	for j in range(i + 1, n):
		if s[i] < s[j]:
			ck_min_i = min(ck_min_i, c[j])
	ck_min.append(ck_min_i)
ans = 10 ** 18
for i in range(n):
	for j in range(i + 1, n):
		if s[i] < s[j]:
			ans = min(ans, c[i] + c[j] + ck_min[j])
if ans == 10 ** 18:
	print(-1)
else:
	print(ans)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
(v1, v2) = (1000000000000000.0, 1000000000000000.0)
ans = 1000000000000000.0
for i in range(1, n):
	(v1, v2) = (1000000000000000.0, 1000000000000000.0)
	for j in range(0, i):
		if s[i] > s[j]:
			v1 = min(v1, c[j])
	for j in range(i + 1, n):
		if s[j] > s[i]:
			v2 = min(v2, c[j])
	ans = min(ans, c[i] + v1 + v2)
if ans == 1000000000000000.0:
	print(-1)
else:
	print(ans)


n = int(input())
ss = list(map(int, input().strip().split()))
cs = list(map(int, input().strip().split()))
dp = [[float('inf')] * 4 for _ in range(n + 1)]
for i in range(1, n + 1):
	dp[i][1] = cs[i - 1]
for i in range(2, n + 1):
	for j in range(2, 4):
		(s, c) = (ss[i - 1], cs[i - 1])
		for k in range(1, i):
			if ss[k - 1] < s:
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + c)
mmin = float('inf')
for i in range(1, 1 + n):
	mmin = min(mmin, dp[i][3])
if mmin == float('inf'):
	print(-1)
else:
	print(mmin)


n = int(input())
a = list(map(int, input().split()))
cost = list(map(int, input().split()))
ans = float('inf')
for i in range(n):
	(m, r) = (float('inf'), float('inf'))
	for j in range(i):
		if a[j] < a[i]:
			m = min(m, cost[j])
	for k in range(i + 1, n):
		if a[k] > a[i]:
			r = min(r, cost[k])
	ans = min(ans, cost[i] + m + r)
print(ans if ans != float('inf') else -1)


from math import inf
n = int(input())
a = input()
a = [int(i) for i in a.split()]
s = input()
s = [int(i) for i in s.split()]
ans = inf
for j in range(1, n - 1):
	(ll, lr) = (inf, inf)
	for q in range(j + 1, n):
		if a[j] < a[q]:
			lr = min(lr, s[q])
	for q in range(j):
		if a[j] > a[q]:
			ll = min(ll, s[q])
	ans = min(ans, ll + lr + s[j])
if ans == inf:
	print(-1)
else:
	print(ans)


def main():
	n = int(input())
	s = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	Max = 2 * sum(c)
	f = [x for x in c]
	for _ in range(2):
		for i in range(n - 1, -1, -1):
			min_fj = Max
			for j in range(i):
				if s[j] < s[i]:
					min_fj = min(f[j], min_fj)
			if min_fj == Max:
				f[i] = Max
			else:
				f[i] = min_fj + c[i]
	min_cost = min(f)
	if min_cost == Max:
		print(-1)
	else:
		print(min_cost)

def __starting_point():
	main()
__starting_point()


def main():
	input()
	displays = list(map(int, input().split()))
	costs = list(map(int, input().split()))
	INF = 10000000000
	dp = []
	for i in range(len(costs)):
		dp.append([costs[i]] + [INF for _ in range(2)])
	result = INF
	for i in range(1, len(costs)):
		for j in range(0, i):
			if displays[j] < displays[i]:
				dp[i][1] = min(dp[j][0] + costs[i], dp[i][1])
				dp[i][2] = min(dp[j][1] + costs[i], dp[i][2])
		result = min(result, dp[i][2])
	if result == INF:
		print(-1)
	else:
		print(result)
main()


import sys

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

def solve(N, S, C):
	dp = [float('inf')] * N
	for i in range(1, N):
		for j in range(i):
			if S[j] < S[i]:
				dp[i] = min(dp[i], C[j] + C[i])
	dp2 = [float('inf')] * N
	for i in range(N - 1, 0, -1):
		for j in range(i + 1, N, 1):
			if S[i] < S[j]:
				dp2[j] = min(dp2[j], dp[i] + C[j])
	ans = min(dp2)
	if ans == float('inf'):
		return -1
	return ans
N = int(input())
S = get_ints()
C = get_ints()
print(solve(N, S, C))


import sys, itertools, math, collections, random

def ia():
	return [int(i) for i in sys.stdin.readline().strip().split(' ')]

def ii():
	return int(sys.stdin.readline().strip())

def istr():
	return sys.stdin.readline().strip()
n = ii()
S = ia()
C = ia()
ans = 10 ** 10
for i in range(n):
	v = S[i]
	left = 10 ** 10
	for j in range(i - 1, -1, -1):
		vl = S[j]
		if vl < v:
			left = min(left, C[j])
	right = 10 ** 10
	for j in range(i + 1, n):
		vr = S[j]
		if vr > v:
			right = min(right, C[j])
	if left < 10 ** 10 and right < 10 ** 10:
		ans = min(ans, C[i] + left + right)
if ans < 10 ** 10:
	print(ans)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
j1 = [float('inf')] * n
j2 = [float('inf')] * n
for i in range(n):
	for j in range(i + 1, n):
		if a[i] < a[j]:
			j1[j] = min(j1[j], b[i] + b[j])
for i in range(n):
	for j in range(i + 1, n):
		if a[i] < a[j]:
			j2[i] = min(j2[i], b[i] + b[j])
ans = min([x[0] + x[1] - b[i] for (i, x) in enumerate(zip(j1, j2))])
if ans == float('inf'):
	print(-1)
else:
	print(ans)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = float('inf')
dp = [[float('inf') for x in range(3)] for u in range(len(s) + 1)]
for i in range(len(s)):
	dp[i][0] = c[i]
	for j in range(1, 3):
		dp[i][j] = float('inf')
		for k in range(i):
			if s[k] < s[i]:
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + c[i])
	ans = min(ans, dp[i][2])
if ans == float('inf'):
	print(-1)
else:
	print(ans)


from sys import *
from math import *
from bisect import *
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
c = list(map(int, stdin.readline().split()))
ans = []
f = 0
for i in range(n):
	c1 = c2 = max(c) + 1
	for j in range(i + 1, n):
		if a[j] > a[i]:
			c1 = min(c1, c[j])
	for j in range(i):
		if a[j] < a[i]:
			c2 = min(c2, c[j])
	if c1 != max(c) + 1 and c2 != max(c) + 1:
		f = 1
		ans.append(c[i] + c1 + c2)
if f == 0:
	print(-1)
else:
	print(min(ans))


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
c_min = []
for i in range(n):
	mini = int(10 ** 18)
	for j in range(i + 1, n):
		if s[i] < s[j]:
			mini = min(mini, c[j])
	c_min.append(mini)
res = int(10 ** 18)
for i in range(n):
	for j in range(i + 1, n):
		if s[i] < s[j]:
			res = min(res, c[i] + c[j] + c_min[j])
print(-1 if res == int(10 ** 18) else res)


from math import inf
n = int(input())
s = tuple(map(int, input().split()))
c = tuple(map(int, input().split()))
ans = inf
for i in range(1, n - 1):
	bef = inf
	aft = inf
	for j in range(i + 1, n):
		if s[j] > s[i]:
			aft = min(aft, c[j])
	for k in range(i):
		if s[k] < s[i]:
			bef = min(bef, c[k])
	ans = min(ans, bef + c[i] + aft)
print(ans if ans < inf else -1)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
minCost = float('inf')
for j in range(1, n - 1):
	curr = s[j]
	minLs = float('inf')
	minMax = float('inf')
	for i in range(j):
		if s[i] < curr:
			minLs = min(minLs, c[i])
	for i in range(j + 1, n):
		if s[i] > curr:
			minMax = min(minMax, c[i])
	if minLs == float('inf') or minMax == float('inf'):
		continue
	minCost = min(minCost, c[j] + minLs + minMax)
print(-1 if minCost == float('inf') else minCost)


n = int(input())
S = [int(x) for x in input().split()]
s = tuple(S)
c = tuple((int(x) for x in input().split()))
S.sort()

def min(x, y):
	if x < y:
		return x
	else:
		return y

def rank(x):
	l = 0
	r = n - 1
	while l < r:
		mid = l + r >> 1
		if S[mid] < x:
			l = mid + 1
		else:
			r = mid
	return l
rk = tuple((rank(x) for x in s))
Min = [10000000000 for i in range(30000)]

def insert(x, l, r, p, v):
	Min[x] = min(Min[x], v)
	if l == r:
		return
	mid = l + r >> 1
	if p > mid:
		insert(x << 1 | 1, mid + 1, r, p, v)
	else:
		insert(x << 1, l, mid, p, v)

def query(x, l, r, L, R):
	if l >= L and r <= R:
		return Min[x]
	mid = l + r >> 1
	ans = 10000000000
	if L <= mid:
		ans = min(ans, query(x << 1, l, mid, L, R))
	if R > mid:
		ans = min(ans, query(x << 1 | 1, mid + 1, r, L, R))
	return ans
dp = list(c)
Min = [10000000000 for i in range(30000)]
for i in range(0, n):
	insert(1, 0, n - 1, rk[i], dp[i])
	dp[i] = c[i]
	if rk[i] == 0:
		dp[i] += 10000000000
	else:
		dp[i] += query(1, 0, n - 1, 0, rk[i] - 1)
Min = [10000000000 for i in range(30000)]
for i in range(0, n):
	insert(1, 0, n - 1, rk[i], dp[i])
	dp[i] = c[i]
	if rk[i] == 0:
		dp[i] += 10000000000
	else:
		dp[i] += query(1, 0, n - 1, 0, rk[i] - 1)
ans = 10000000000
for i in dp:
	ans = min(ans, i)
if ans > 3000000000:
	print(-1)
else:
	print(ans)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
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')
import collections, re, itertools, statistics, math
from collections import *
from itertools import *
from statistics import *
from math import *
from re import *
mod = int(1000000000.0 + 7)
imin = -2147483648
imax = 2147483647
true = True
false = False
none = None
inp = lambda : input()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
L = lambda : list(M())
Yes = lambda : print('Yes')
No = lambda : print('No')
YES = lambda : print('YES')
NO = lambda : print('NO')

def IO(controll):
	if controll == false:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		pass

def true_yes(statement):
	return YES() if statement else NO()

def state(statement, one, two):
	print(one if statement else two)

def swap(a, b):
	(a, b) = (b, a)

def debug(something):
	print(*something)

def prec(a):
	return '{0:.7f}'.format(a)

def binary_search(arr, low, high, x):
	while low <= high:
		mid = low + (high - low) // 2
		if arr[mid] == x:
			return [mid, true]
		elif arr[mid] > x:
			high = mid - 1
		else:
			low = mid - 1
	return [-1, false]

def kabraji_ka_totka():
	IO(1)
	n = I()
	dis = L()
	costs = L()
	temp = [imax] * n
	temp1 = [imax] * n
	for i in range(1, n):
		for j in range(0, i):
			if dis[j] < dis[i]:
				temp[i] = min(temp[i], costs[i] + costs[j])
	res = imax
	for i in range(2, n):
		for j in range(1, i):
			if dis[j] < dis[i]:
				temp1[i] = min(temp1[i], temp[j] + costs[i])
				res = min(res, temp1[i])
	state(res == imax, -1, res)
kabraji_ka_totka()


n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
mincost = float('inf')
for i in range(1, n - 1):
	minleft = float('inf')
	minright = float('inf')
	for j in range(0, i):
		if s[j] < s[i]:
			minleft = min(minleft, c[j])
	for j in range(i + 1, n):
		if s[j] > s[i]:
			minright = min(minright, c[j])
	mincost = min(mincost, minleft + minright + c[i])
if mincost < float('inf'):
	print(mincost)
else:
	print(-1)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
INF = 10 ** 18
dp2 = [INF] * n
for i in range(n):
	for j in range(0, i):
		if s[i] > s[j] and dp2[i] > c[i] + c[j]:
			dp2[i] = c[i] + c[j]
dp3 = [INF] * n
for i in range(n):
	for j in range(0, i):
		if s[i] > s[j] and dp3[i] > c[i] + dp2[j]:
			dp3[i] = c[i] + dp2[j]
ans = min(dp3)
if ans == INF:
	print(-1)
else:
	print(ans)


import math
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
maxValue = float('inf')
ans = float('inf')
esquerdaMin = [0] * n
direitaMin = [0] * n
esquerdaMin[0] = c[0]
for i in range(1, n):
	esquerdaMin[i] = min(c[i], esquerdaMin[i - 1])
direitaMin[n - 1] = c[n - 1]
for i in range(n - 2, -1, -1):
	direitaMin[i] = min(c[i], direitaMin[i + 1])
minTamanhoE = [0] * n
minTamanhoD = [0] * n
minTamanhoE[0] = s[0]
for i in range(1, n):
	minTamanhoE[i] = min(s[i], minTamanhoE[i - 1])
minTamanhoD[n - 1] = s[n - 1]
for i in range(n - 2, -1, -1):
	minTamanhoD[i] = max(s[i], minTamanhoD[i + 1])
preco = [(c[j], j) for j in range(1, n - 1)]
preco.sort()
for (k, j) in preco:
	if esquerdaMin[j - 1] + c[j] + direitaMin[j + 1] >= ans:
		continue
	if minTamanhoE[j - 1] >= s[j] or s[j] >= minTamanhoD[j + 1]:
		continue
	a = maxValue
	for i in range(j):
		if s[i] < s[j]:
			a = min(a, c[i])
	b = maxValue
	for k in range(j + 1, n):
		if s[j] < s[k]:
			b = min(b, c[k])
	curr = a + b + c[j]
	ans = min(ans, curr)
if ans == maxValue * 3:
	ans = -1
print(ans)


from sys import stdin, stdout
nmbr = lambda : int(stdin.readline())
lst = lambda : list(map(int, stdin.readline().split()))
for _ in range(1):
	n = nmbr()
	a = lst()
	b = lst()
	ans = PI = float('inf')
	dp = [[PI for _ in range(4)] for _ in range(n)]
	for i in range(n):
		dp[i][1] = b[i]
		for j in range(i):
			if a[j] < a[i]:
				dp[i][2] = min(dp[i][2], dp[j][1] + b[i])
				dp[i][3] = min(dp[i][3], dp[j][2] + b[i])
				ans = min(ans, dp[i][3])
	print(ans if ans != PI else -1)


n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
(smaller, greater, ans) = [10 ** 9] * 3
(flag1, flag2, done) = [0] * 3
for i in range(1, n):
	for j in range(i):
		if s[j] < s[i]:
			smaller = min(smaller, c[j])
			flag1 = 1
	for j in range(i + 1, n):
		if s[j] > s[i]:
			greater = min(greater, c[j])
			flag2 = 1
	if flag1 and flag2:
		ans = min(ans, smaller + greater + c[i])
		done = 1
	(smaller, greater) = (10 ** 9, 10 ** 9)
	(flag1, flag2) = (0, 0)
if not done:
	print(-1)
else:
	print(ans)


from sys import stdin, stdout
nmbr = lambda : int(stdin.readline())
lst = lambda : list(map(int, stdin.readline().split()))
for _ in range(1):
	n = nmbr()
	a = lst()
	b = lst()
	dp = [0] * n
	for i in range(n):
		v = float('inf')
		for j in range(i + 1, n):
			if a[j] > a[i]:
				v = min(v, b[i] + b[j])
		dp[i] = v
	for i in range(n):
		v = float('inf')
		for j in range(i + 1, n):
			if a[j] > a[i]:
				v = min(v, b[i] + dp[j])
		dp[i] = v
	ans = min(dp)
	print(ans if ans != float('inf') else -1)


from bisect import *
import math
from collections import *
from heapq import *
from itertools import *
inf = 10 ** 18
mod = 10 ** 9 + 7
n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
minn = inf
for j in range(1, n - 1):
	cost = c[j]
	temp1 = inf
	temp2 = inf
	for i in range(j):
		if s[i] < s[j]:
			temp1 = min(temp1, c[i])
	for k in range(j + 1, n):
		if s[j] < s[k]:
			temp2 = min(temp2, c[k])
	minn = min(temp1 + temp2 + cost, minn)
if minn < inf:
	print(minn)
else:
	print(-1)


n = int(input())
s = list(map(int, input().split()))
c = list(map(int, input().split()))
num = float('inf')
rec1 = [float('inf')] * n
rec2 = [float('inf')] * n
for i in range(n):
	for j in range(i + 1, n):
		if s[i] < s[j] and rec1[i] > c[j]:
			rec1[i] = c[j]
for i in range(1, n):
	for j in range(i):
		if s[j] < s[i] and rec2[i] > c[j]:
			rec2[i] = c[j]
for i in range(n):
	num = min(num, rec1[i] + c[i] + rec2[i])
if num == float('inf'):
	print(-1)
else:
	print(num)


n = int(input())
s = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
cost = min((min([30000000000.0] + [c[j] for j in range(i) if s[j] < s[i]]) + c[i] + min([30000000000.0] + [c[k] for k in range(i + 1, n) if s[k] > s[i]]) for i in range(n)))
if cost >= 30000000000.0:
	cost = -1
print(cost)