using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);

            for (int i = 0; i < n; i++)
            {
                if (result.CanSet(size, i))
                {
                    result.Set(i);
                }
                else
                {
                    var twos = twosIndexes[i];
                    if (result.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            if (resultNode2.CanSet(size, i))
            {
                resultNode2.Set(i);
            }
            else
            {
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = cost.Max();
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

    private static int CalculateCost(int a, int b, int c, List<int> size, List<int> cost)
    {
        if (a < b && b < c && size[a] < size[b] && size[b] < size[c])
        {
            return cost[a] + cost[b] + cost[c];
        }

        return -1;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]);
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;
        }
        else
        {
            Index2 = index;
        }
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    internal bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]) || (Index2 != -1 && Index3 == -1 && size[Index2] < size[i]);
    }

    internal void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;

            return;
        }

        if (Index2 == -1)
        {
            Index2 = index;

            return;
        }

        if (Index3 == -1)
        {
            Index3 = index;

            return;
        }
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);
            var first = true;

            for (int i = 0; i < n; i++)
            {

                if (first && twosIndexes[i].IsValid())
                {
                    result = new ResultNode3(twosIndexes[i].Index1, twosIndexes[i].Index2, i);
                    first = false;
                }
                else
                {
                    var twos = twosIndexes[i];
                    if (result.IsValid() && twos.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);
        var first = true;

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            if (first && onesIndexes[i] != -1)
            {
                resultNode2 = new ResultNode2(onesIndexes[i], i);
                first = false;
            }
            else
            {
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = int.MaxValue;
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

    private static int CalculateCost(int a, int b, int c, List<int> size, List<int> cost)
    {
        if (a < b && b < c && size[a] < size[b] && size[b] < size[c])
        {
            return cost[a] + cost[b] + cost[c];
        }

        return -1;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}


using System;
using System.Linq;

internal class Program
{
    private static void Main(string[] args)
    {
        var n = Console.ReadLine();
        var sArray = Console.ReadLine().Split();
        var cArray = Console.ReadLine().Split();

        cArray.Any(x => true);

        GetMin2(sArray, cArray, int.Parse(n));
    }

    private static Result GetMin2(string[] sArray, string[] cArray, int index)
    {
        return null;
    }

    private class Result
    {
        public int S1;
        public int C1;
        public int S2;
        public int C2;
    }
}


using System;
using System.Linq;

internal class Program
{
    private static void Main(string[] args)
    {
        var n = Console.ReadLine();
        var sArray = Console.ReadLine().Split().ToList();
        var cArray = Console.ReadLine().Split().ToList();

        cArray.ForEach(x =>
        {
            Console.WriteLine("res");
        });

        //GetMin2(sArray, cArray, int.Parse(n));
    }

    //private static Result GetMin2(string[] sArray, string[] cArray, int index)
    //{
    //    if(index == 0)
    //    {
    //        return
    //    }

    //    return null;
    //}

    private class Result
    {
        public ResultNode First;
        public ResultNode Second;
    }

    private class ResultNode
    {
        public int S1;
        public int C1;
        public int Index;
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);

            for (int i = 0; i < n; i++)
            {
                if (result.CanSet(size, i))
                {
                    result.Set(i);
                }
                else
                {
                    var twos = twosIndexes[i];
                    if (result.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);

        for (int i = 0; i < n; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            if (resultNode2.CanSet(size, i))
            {
                resultNode2.Set(i);
            }
            else
            {
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = int.MaxValue;
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < n; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

    private static int CalculateCost(int a, int b, int c, List<int> size, List<int> cost)
    {
        if (a < b && b < c && size[a] < size[b] && size[b] < size[c])
        {
            return cost[a] + cost[b] + cost[c];
        }

        return -1;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]);
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;
        }
        else
        {
            Index2 = index;
        }
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    internal bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]) || (Index2 != -1 && Index3 == -1 && size[Index2] < size[i]);
    }

    internal void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;

            return;
        }

        if (Index2 == -1)
        {
            Index2 = index;

            return;
        }

        if (Index3 == -1)
        {
            Index3 = index;

            return;
        }
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var size = Console.ReadLine().Split().Select(int.Parse).ToList();
        var cost = Console.ReadLine().Split().Select(int.Parse).ToList();

        var result = new ResultNode3(-1, -1, -1); ;

        if (n >= 3)
        {
            var onesIndexes = GetOnesIndexes(size, cost, n);

            var twosIndexes = GetTwosIndexes(size, cost, onesIndexes, n);
            var first = true;

            for (int i = 0; i < n; i++)
            {

                if (first && twosIndexes[i].IsValid())
                {
                    result = new ResultNode3(twosIndexes[i].Index1, twosIndexes[i].Index2, i);
                    first = false;
                }
                else
                {

                    //if (result.CanSet(size, i))
                    //{
                    //    result.Set(i);
                    //}
                    //else
                    //{
                    var twos = twosIndexes[i];
                    if (result.IsValid() && twos.IsValid() && result.GetCost(cost) > (cost[i] + twos.GetCost(cost)))
                    {
                        result = new ResultNode3(twos.Index1, twos.Index2, i);
                    }
                    //}
                }

            }
        }

        Console.WriteLine(result.GetCost(cost));
    }

    private static List<ResultNode2> GetTwosIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int n)
    {
        var result = new List<ResultNode2>();

        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostCoupleIndexes(size, cost, onesIndexes, i, n));
        }

        return result;
    }

    private static ResultNode2 GetMinCostCoupleIndexes(List<int> size, List<int> cost, List<int> onesIndexes, int upperLimitIndex, int n)
    {
        var upperLimitSize = size[upperLimitIndex];

        var resultNode2 = new ResultNode2(-1, -1);
        var first = true;

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (size[i] >= upperLimitSize)
                continue;

            //new
            if (first && onesIndexes[i] != -1)
            {
                resultNode2 = new ResultNode2(onesIndexes[i], i);
                first = false;
            }
            else
            {

                //if (resultNode2.CanSet(size, i))
                //{
                //    resultNode2.Set(i);
                //}
                //else
                //{
                if (resultNode2.IsValid() && onesIndexes[i] != -1 && resultNode2.GetCost(cost) > (cost[i] + cost[onesIndexes[i]]))
                {
                    resultNode2 = new ResultNode2(onesIndexes[i], i);
                }
                //}
            }
        }

        return resultNode2;
    }

    private static List<int> GetOnesIndexes(List<int> size, List<int> cost, int n)
    {
        var result = new List<int>();
        for (int i = 0; i < n; i++)
        {
            result.Add(GetMinCostElemIndex(size, cost, i, n));
        }

        return result;
    }

    private static int GetMinCostElemIndex(List<int> size, List<int> cost, int upperLimitIndex, int n)
    {
        var min = int.MaxValue;
        var minIndex = -1;
        var upperLimitSize = size[upperLimitIndex];

        for (int i = 0; i < upperLimitIndex; i++)
        {
            if (cost[i] < min && size[i] < upperLimitSize)
            {
                min = cost[i];
                minIndex = i;
            }
        }

        return minIndex;
    }

    private static int CalculateCost(int a, int b, int c, List<int> size, List<int> cost)
    {
        if (a < b && b < c && size[a] < size[b] && size[b] < size[c])
        {
            return cost[a] + cost[b] + cost[c];
        }

        return -1;
    }

}

internal class ResultNode2
{
    public int Index1;
    public int Index2;

    public bool IsValid()
    {
        return Index1 != -1 && Index2 != -1;
    }

    public bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]);
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2];
        }

        return -1;
    }

    public void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;
        }
        else
        {
            Index2 = index;
        }
    }

    public ResultNode2(int index1, int index2)
    {
        Index1 = index1;
        Index2 = index2;
    }
}

internal class ResultNode3
{
    public int Index1;
    public int Index2;
    public int Index3;

    internal bool IsValid()
    {
        return Index1 != -1 && Index2 != -1 && Index3 != -1;
    }

    internal bool CanSet(List<int> size, int i)
    {
        return Index1 == -1 || (Index2 == -1 && size[Index1] < size[i]) || (Index2 != -1 && Index3 == -1 && size[Index2] < size[i]);
    }

    internal void Set(int index)
    {
        if (Index1 == -1)
        {
            Index1 = index;

            return;
        }

        if (Index2 == -1)
        {
            Index2 = index;

            return;
        }

        if (Index3 == -1)
        {
            Index3 = index;

            return;
        }
    }

    public int GetCost(List<int> cost)
    {
        if (IsValid())
        {
            return cost[Index1] + cost[Index2] + cost[Index3];
        }

        return -1;
    }

    public ResultNode3(int index1, int index2, int index3)
    {
        Index1 = index1;
        Index2 = index2;
        Index3 = index3;
    }

}


 public class Program
    {
        private static void Main(string[] args)
        {
            var n = Console.ReadLine();
            var sArray = Console.ReadLine().Split();
            var cArray = Console.ReadLine().Split();

            GetMin2(sArray, cArray, n);
        }

        private Result GetMin2(string[] sArray, string[] cArray, int index)
        {
            return null;
        }

        private class Result
        {
            public int S1;
            public int C1;
            public int S2;
            public int C2;
        }
    }


using System;

internal class Program
{
    private static void Main(string[] args)
    {
        var n = Console.ReadLine();
        var sArray = Console.ReadLine().Split();
        var cArray = Console.ReadLine().Split();

        GetMin2(sArray, cArray, n);
    }

    private Result GetMin2(string[] sArray, string[] cArray, int index)
    {
        return null;
    }

    private class Result
    {
        public int S1;
        public int C1;
        public int S2;
        public int C2;
    }
}


using System;

internal class Program
{
    private static void Main(string[] args)
    {
        var n = Console.ReadLine();
        var sArray = Console.ReadLine().Split();
        var cArray = Console.ReadLine().Split();

        GetMin2(sArray, cArray, int.Parse(n));
    }

    private static Result GetMin2(string[] sArray, string[] cArray, int index)
    {
        return null;
    }

    private class Result
    {
        public int S1;
        public int C1;
        public int S2;
        public int C2;
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = int.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
            Console.ReadKey();
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = (long)(Math.Pow(10, 8) + 2);

                for (int j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);
                    }
                }

                cheapestPairPrices[i] = minimalSum;
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = (long)(Math.Pow(10, 8) + 2);

                for (int j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = int.MaxValue;

            for (int i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == int.MaxValue ? -1 : minValue;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestPairPrices[i] = -1;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (long i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (cheapestPairPrices[j] == -1)
                        continue;

                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
         }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestPairPrices[i] = -1;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (cheapestPairPrices[j] == -1)
                        continue;

                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static int[] money = new int[] { 1, 5, 10, 20, 100 };

        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            //cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                //var minimalSum = (long)(Math.Pow(10, 8) + 2);
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
		}

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (int i = 1; i < fonts.Length; i++)
            {
                cheapestPairPrices[i] = -1;
                var minimalSum = long.MaxValue;

                for (int j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                cheapestTrioPrices[i] = -1;
                var minimalSum = long.MaxValue;

                for (int j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j] && cheapestPairPrices[j] != -1)
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }
	}
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestPairPrices[i] = -1;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j] && cheapestPairPrices[j] != -1)
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }
	}
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestPairPrices[i] = -1;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j] && cheapestPairPrices[j] != -1)
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }
	}
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split().Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestPairPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestPairPrices[i] = -1;
                    }
                }
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = long.MaxValue;

                for (long j = 1; j < i; j++)
                {
                    if (cheapestPairPrices[j] == -1)
                        continue;

                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
    class Program
    {
        static int[] money = new int[] { 1, 5, 10, 20, 100 };

        static void Main(string[] args)
        {
            var numberOfBanners = long.Parse(Console.ReadLine());
            var fonts = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();
            var prices = Console.ReadLine().Split(' ').Select(i => long.Parse(i)).ToArray();

            var result = CheapestPriceBoards(fonts, prices);

            Console.WriteLine(result);
        }

        private static long CheapestPriceBoards(long[] fonts, long[] prices)
        {
            long[] cheapestPairPrices = new long[fonts.Length];

            cheapestPairPrices[0] = -1;

            for (long i = 1; i < fonts.Length; i++)
            {
                var minimalSum = (long)(Math.Pow(10, 8) + 2);

                for (long j = 0; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = prices[i] + prices[j];
                        minimalSum = Math.Min(minimalSum, currentSum);
                    }
                }

                cheapestPairPrices[i] = minimalSum;
            }

            long[] cheapestTrioPrices = new long[cheapestPairPrices.Length];

            cheapestTrioPrices[0] = -1;
            cheapestTrioPrices[1] = -1;

            for (int i = 2; i < fonts.Length; i++)
            {
                var minimalSum = (long)(Math.Pow(10, 8) + 2);

                for (long j = 1; j < i; j++)
                {
                    if (fonts[i] > fonts[j])
                    {
                        var currentSum = cheapestPairPrices[j] + prices[i];
                        minimalSum = Math.Min(minimalSum, currentSum);

                        cheapestTrioPrices[i] = minimalSum;
                    }
                    else
                    {
                        cheapestTrioPrices[i] = -1;
                    }
                }
            }

            long minValue = long.MaxValue;

            for (long i = 2; i < cheapestTrioPrices.Length; i++)
            {
                if (cheapestTrioPrices[i] < minValue && cheapestTrioPrices[i] != -1)
                    minValue = cheapestTrioPrices[i];
            }

            return minValue == long.MaxValue ? -1 : minValue;
        }

    }
 }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TriTablo
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            string[] p = Console.ReadLine().Split();
            int[] s = new int[n];
            for (int i = 0; i < n; i++) s[i] = int.Parse(p[i]);

            p = Console.ReadLine().Split();
            int[] c = new int[n];
            for (int i = 0; i < n; i++) c[i] = int.Parse(p[i]);

            int[,] minCosts = new int[n, 2];

            for (int i = 0; i < n; i++)
            {
                minCosts[i, 0] = -1;
                minCosts[i, 1] = -1;
            }
            int total = int.MaxValue;
            bool possible = false;
            for (int i = 1; i < n; i++)
            {
                int min = int.MaxValue;
                int minSumOfTwo = int.MaxValue;
                for (int j = 0; j < i; j++)
                {
                    if (s[i] > s[j])
                    {
                        min = Math.Min(min, c[j]);

                        if (minCosts[j, 0] != -1)
                            minSumOfTwo = Math.Min(minCosts[j, 0] + c[j], minSumOfTwo);
                    }
                }
                minCosts[i, 0] = min;
                minCosts[i, 1] = minSumOfTwo;
                if (minSumOfTwo <int.MaxValue)
                {
                    possible = true;
                    total = Math.Min(minSumOfTwo + c[i], total);
                }
            }

            if (possible)
                Console.WriteLine(total);
            else
                Console.WriteLine(-1);

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TriTablo
{
    class Program
    {
        static void Main(string[] args)
        {
            long n = long.Parse(Console.ReadLine());

            string[] p = Console.ReadLine().Split();
            long[] s = new long[n];
            for (long i = 0; i < n; i++) s[i] = long.Parse(p[i]);

            p = Console.ReadLine().Split();
            long[] c = new long[n];
            for (long i = 0; i < n; i++) c[i] = long.Parse(p[i]);

            long[,] minCosts = new long[n, 2];

            for (long i = 0; i < n; i++)
            {
                minCosts[i, 0] = long.MaxValue;
                minCosts[i, 1] = long.MaxValue;
            }
            long total = long.MaxValue;
            bool possible = false;
            for (long i = 1; i < n; i++)
            {
                long min = long.MaxValue;
                long minSumOfTwo = long.MaxValue;
                for (long j = 0; j < i; j++)
                {
                    if (s[i] > s[j])
                    {
                        min = Math.Min(min, c[j]);

                        if (minCosts[j, 0] <long.MaxValue)
                            minSumOfTwo = Math.Min(minCosts[j, 0] + c[j], minSumOfTwo);
                    }
                }
                minCosts[i, 0] = min;
                minCosts[i, 1] = minSumOfTwo;
                if (minSumOfTwo <long.MaxValue)
                {
                    possible = true;
                    total = Math.Min(minSumOfTwo + c[i], total);
                }
            }

            if (possible)
                Console.WriteLine(total);
            else
                Console.WriteLine(-1);

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TriTablo
{
    class Program
    {
        static void Main(string[] args)
        {
            long n = long.Parse(Console.ReadLine());

            string[] p = Console.ReadLine().Split();
            long[] s = new long[n];
            for (long i = 0; i < n; i++) s[i] = long.Parse(p[i]);

            p = Console.ReadLine().Split();
            long[] c = new long[n];
            for (long i = 0; i < n; i++) c[i] = long.Parse(p[i]);

            long[,] minCosts = new long[n, 2];

            for (long i = 0; i < n; i++)
            {
                minCosts[i, 0] = -1;
                minCosts[i, 1] = -1;
            }
            long total = long.MaxValue;
            bool possible = false;
            for (long i = 1; i < n; i++)
            {
                long min = long.MaxValue;
                long minSumOfTwo = long.MaxValue;
                for (long j = 0; j < i; j++)
                {
                    if (s[i] > s[j])
                    {
                        min = Math.Min(min, c[j]);

                        if (minCosts[j, 0] != -1)
                            minSumOfTwo = Math.Min(minCosts[j, 0] + c[j], minSumOfTwo);
                    }
                }
                minCosts[i, 0] = min;
                minCosts[i, 1] = minSumOfTwo;
                if (minSumOfTwo <long.MaxValue)
                {
                    possible = true;
                    total = Math.Min(minSumOfTwo + c[i], total);
                }
            }

            if (possible)
                Console.WriteLine(total);
            else
                Console.WriteLine(-1);

        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Three_displays
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            writer.WriteLine(Solve());
            writer.Flush();
        }

        private static long Solve()
        {
            int n = Next();

            var s = new int[n];
            for (int i = 0; i < n; i++)
            {
                s[i] = Next();
            }
            var c = new int[n];
            for (int i = 0; i < n; i++)
            {
                c[i] = Next();
            }
            List<int> d = s.Distinct().OrderBy(t => t).ToList();
            for (int i = 0; i < n; i++)
            {
                s[i] = d.IndexOf(s[i]);
            }

            int m = d.Count + 1;
            var mm = new int[m];
            for (int i = 0; i < mm.Length; i++)
            {
                mm[i] = int.MaxValue;
            }
            var tree = new SegmentTree(mm);
            tree.Modify(s[0], c[0]);
            var a = new long[n];
            for (int i = 1; i < n; i++)
            {
                a[i] = c[i] + tree.Query(0, s[i]);
                tree.Modify(s[i], c[i]);
            }
            long min = int.MaxValue;
            tree = new SegmentTree(mm);

            tree.Modify(s[n - 1], c[n - 1]);
            for (int i = n - 2; i > 0; i--)
            {
                min = Math.Min(min, a[i] + tree.Query(s[i] + 1, m));
                tree.Modify(s[i], c[i]);
            }
            return min >= int.MaxValue ? -1 : min;
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }

        #region Nested type: SegmentTree

        public class SegmentTree
        {
            private readonly int n;
            private readonly int[] t;

            public SegmentTree(int[] array)
            {
                n = array.Length;
                t = new int[2*n];
                Array.Copy(array, 0, t, n, n);
                Build();
            }

            private void Build()
            {
                for (int i = n - 1; i > 0; --i) t[i] = Math.Min(t[i << 1], t[i << 1 | 1]);
            }

            public void Modify(int p, int value)
            {
                for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = Math.Min(t[p], t[p ^ 1]);
            }

            public int Query(int l, int r)
            {
                int res = int.MaxValue;
                for (l += n, r += n; l < r; l >>= 1, r >>= 1)
                {
                    if ((l & 1) == 1) res = Math.Min(res, t[l++]);
                    if ((r & 1) == 1) res = Math.Min(res, t[--r]);
                }
                return res;
            }
        }

        #endregion
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Three_displays
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            writer.WriteLine(Solve());
            writer.Flush();
        }

        private static long Solve()
        {
            int n = Next();

            var s = new int[n];
            for (int i = 0; i < n; i++)
            {
                s[i] = Next();
            }
            var c = new int[n];
            for (int i = 0; i < n; i++)
            {
                c[i] = Next();
            }
            List<int> d = s.Distinct().OrderBy(t => t).ToList();
            for (int i = 0; i < n; i++)
            {
                s[i] = d.IndexOf(s[i]);
            }

            int m = d.Count + 1;
            var mm = new int[m];
            for (int i = 0; i < mm.Length; i++)
            {
                mm[i] = int.MaxValue;
            }
            var tree = new SegmentTree(mm);
            tree.Modify(s[0], c[0]);
            var a = new long[n];
            for (int i = 1; i < n; i++)
            {
                a[i] = (long)c[i] + tree.Query(0, s[i]);
                tree.Modify(s[i], c[i]);
            }
            long min = int.MaxValue;
            tree = new SegmentTree(mm);

            tree.Modify(s[n - 1], c[n - 1]);
            for (int i = n - 2; i > 0; i--)
            {
                min = Math.Min(min, a[i] + tree.Query(s[i] + 1, m));
                tree.Modify(s[i], c[i]);
            }
            return min >= int.MaxValue ? -1 : min;
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }

        #region Nested type: SegmentTree

        public class SegmentTree
        {
            private readonly int n;
            private readonly int[] t;

            public SegmentTree(int[] array)
            {
                n = array.Length;
                t = new int[2*n];
                Array.Copy(array, 0, t, n, n);
                Build();
            }

            private void Build()
            {
                for (int i = n - 1; i > 0; --i) t[i] = Math.Min(t[i << 1], t[i << 1 | 1]);
            }

            public void Modify(int p, int value)
            {
                for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = Math.Min(t[p], t[p ^ 1]);
            }

            public int Query(int l, int r)
            {
                int res = int.MaxValue;
                for (l += n, r += n; l < r; l >>= 1, r >>= 1)
                {
                    if ((l & 1) == 1) res = Math.Min(res, t[l++]);
                    if ((r & 1) == 1) res = Math.Min(res, t[--r]);
                }
                return res;
            }
        }

        #endregion
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces_987C
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] ss = Console.ReadLine().Split();
            string[] cs = Console.ReadLine().Split();

            int[] s = new int[n];
            int[] c = new int[n];

            for(int i = 0; i< n; i++)
            {
                s[i] = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToInt32(cs[i]);
            }

            int[,] dp = new int[n, 3];

            for(int i = 0; i< n; i++)
            {
                dp[i, 0] = c[i];

                for(int j = 0; j < i; j++)
                {
                    if (s[i] > s[j])
                    {
                        for (int k = 0; k < 2; k++)
                        {
                            if(dp[j,k] > 0)
                            {
                                if(dp[j,k+1] != 0)
                                {
                                    dp[i, k + 1] = Math.Min(dp[i, k + 1], dp[j, k] + c[i]);
                                }
                                else
                                {
                                    dp[i, k + 1] = dp[j, k] + c[i];
                                }

                            }
                        }
                    }
                }
            }

            int min = Int32.MaxValue;

            for(int i = 0; i<n; i++)
            {
                if(dp[i,2] != 0)
                {
                    min = Math.Min(min, dp[i, 2]);
                }

            }

            if(min == Int32.MaxValue)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces_987C
{
    class Program
    {
        static void Main(string[] args)
        {
            long n = Convert.ToInt64(Console.ReadLine());
            string[] ss = Console.ReadLine().Split();
            string[] cs = Console.ReadLine().Split();

            long[] s = new long[n];
            long[] c = new long[n];

            for(long i = 0; i< n; i++)
            {
                s[i] = Convert.ToInt64(ss[i]);
                c[i] = Convert.ToInt64(cs[i]);
            }

            long[,] dp = new long[n, 3];

            for(long i = 0; i< n; i++)
            {
                dp[i, 0] = c[i];

                for(long j = 0; j < i; j++)
                {
                    if (s[i] > s[j])
                    {
                        for (long k = 0; k < 2; k++)
                        {
                            if(dp[j,k] > 0)
                            {
                                if(dp[j,k+1] != 0)
                                {
                                    dp[i, k + 1] = Math.Min(dp[i, k + 1], dp[j, k] + c[i]);
                                }
                                else
                                {
                                    dp[i, k + 1] = dp[j, k] + c[i];
                                }

                            }
                        }
                    }
                }
            }

            long min = Int64.MaxValue;

            for(long i = 0; i<n; i++)
            {
                if(dp[i,2] != 0)
                {
                    min = Math.Min(min, dp[i, 2]);
                }

            }

            if(min == Int64.MaxValue)
            {
                Console.WriteLine(-1);
            }
            else
            {
                Console.WriteLine(min);
            }

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces_987C
{
    class Program
    {
        static void Main(string[] args)
        {
            long n = Convert.ToInt64(Console.ReadLine());
            string[] ss = Console.ReadLine().Split();
            string[] cs = Console.ReadLine().Split();

            long[] s = new long[n];
            long[] c = new long[n];

            for(long i = 0; i< n; i++)
            {
                s[i] = Convert.ToInt64(ss[i]);
                c[i] = Convert.ToInt64(cs[i]);
            }

            long[,] dp = new long[n, 3];

            for(int i = 0; i<n; i++)
            {
                dp[i,0] = c[i];
                for(int j = 1; j<3; j++)
                {
                    dp[i,j] = 123456789000;
                    for(int k = 0; k< i; k++)
                    {
                        if(s[k] < s[i])
                        {
                            dp[i, j] = Math.Min(dp[i,j], dp[k,j - 1] + c[i]);
                        }
                    }
                }
            }

            long min = Int64.MaxValue;
            for(int i = 0; i< n; i++)
            {
                min = Math.Min(min, dp[i,2]);
            }
            if (min == 123456789000)
            {
                min = -1;
            }
            Console.WriteLine(min);

        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace CF
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var sr = new InputReader(Console.In))
//			using (var sr = new InputReader(new StreamReader("input.txt")))
            using (var sw = Console.Out)
                //using (var sw = new StreamWriter("output.txt"))
            using (var task = new Task(sr, sw)) {
                task.Solve();
//                Console.ReadKey();
            }
        }
    }

    internal class Task : IDisposable
    {
        private readonly InputReader sr;
        private readonly TextWriter sw;
        private bool isDispose;

        public Task(InputReader sr, TextWriter sw)
        {
            this.sr = sr;
            this.sw = sw;
        }

        public void Solve()
        {
            var n = sr.NextInt32();
            var fonts = sr.ReadArrayOfInt32();
            var costs = sr.ReadArrayOfInt32();
            const int max = (int)1e9;
            var bests = Enumerable.Repeat(max, n).ToArray();
            for (var i = 0; i < fonts.Length; i++) {
                for (var j = i + 1; j < fonts.Length; j++) {
                    if (fonts[j] > fonts[i]) {
                        bests[i] = Math.Min(bests[i], costs[j]);
                    }
                }
            }

            var answ = max;
            for (var i = 0; i < fonts.Length; i++) {
                for (var j = i + 1; j < fonts.Length; j++) {
                    var curr = costs[i] + costs[j] + bests[j];
                    if (curr < max) {
                        answ = Math.Min(curr, answ);
                    }
                }
            }

            if (answ == max) {
                sw.WriteLine(-1);
            }
            else {
                sw.WriteLine(answ);
            }
        }

        ~Task()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDispose) {
                if (disposing) {
                    if(sr != null)
                        sr.Dispose();

                    if(sw != null)
                        sw.Dispose();
                }

                isDispose = true;
            }
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;
    private string[] buffer;
    private int seek;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(ReadNextToken());
    }

    private string ReadNextToken()
    {
        if (buffer == null || seek == buffer.Length) {
            seek = 0;
            buffer = NextSplitStrings();
        }

        return buffer[seek++];
    }

    public long NextInt64()
    {
        return Int64.Parse(ReadNextToken());
    }

    public int[] ReadArrayOfInt32()
    {
        return ReadArray(Int32.Parse);
    }

    public long[] ReadArrayOfInt64()
    {
        return ReadArray(Int64.Parse);
    }

    public string[] NextSplitStrings()
    {
        return NextString()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
            .Select(s => func(s, CultureInfo.InvariantCulture))
            .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
            str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();

            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace CF
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var sr = new InputReader(Console.In))
//			using (var sr = new InputReader(new StreamReader("input.txt")))
            using (var sw = Console.Out)
                //using (var sw = new StreamWriter("output.txt"))
            using (var task = new Task(sr, sw)) {
                task.Solve();
//                Console.ReadKey();
            }
        }
    }

    internal class Task : IDisposable
    {
        private readonly InputReader sr;
        private readonly TextWriter sw;
        private bool isDispose;

        public Task(InputReader sr, TextWriter sw)
        {
            this.sr = sr;
            this.sw = sw;
        }

        public void Solve()
        {
            var n = sr.NextInt32();
            var fonts = sr.ReadArrayOfInt32();
            var costs = sr.ReadArrayOfInt32();
            const int max = (int)1e9;
            var bests = Enumerable.Repeat(max, n).ToArray();
            for (var i = 0; i < fonts.Length; i++) {
                for (var j = i + 1; j < fonts.Length; j++) {
                    if (fonts[j] > fonts[i]) {
                        bests[i] = Math.Min(bests[i], costs[j]);
                    }
                }
            }

            var answ = max;
            for (var i = 0; i < fonts.Length; i++) {
                for (var j = i + 1; j < fonts.Length; j++) {
                    if (fonts[j] > fonts[i]) {
                        var curr = costs[i] + costs[j] + bests[j];
                        if (curr < max) {
                            answ = Math.Min(curr, answ);
                        }
                    }
                }
            }

            if (answ == max) {
                sw.WriteLine(-1);
            }
            else {
                sw.WriteLine(answ);
            }
        }

        ~Task()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDispose) {
                if (disposing) {
                    if(sr != null)
                        sr.Dispose();

                    if(sw != null)
                        sw.Dispose();
                }

                isDispose = true;
            }
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;
    private string[] buffer;
    private int seek;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(ReadNextToken());
    }

    private string ReadNextToken()
    {
        if (buffer == null || seek == buffer.Length) {
            seek = 0;
            buffer = NextSplitStrings();
        }

        return buffer[seek++];
    }

    public long NextInt64()
    {
        return Int64.Parse(ReadNextToken());
    }

    public int[] ReadArrayOfInt32()
    {
        return ReadArray(Int32.Parse);
    }

    public long[] ReadArrayOfInt64()
    {
        return ReadArray(Int64.Parse);
    }

    public string[] NextSplitStrings()
    {
        return NextString()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
            .Select(s => func(s, CultureInfo.InvariantCulture))
            .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
            str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();

            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace C_ThreeDisplays
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
            uint[] sizes = Console.ReadLine().Split(' ').Select(uint.Parse).Concat(new uint[] { uint.MaxValue }).ToArray();
            uint[] costs = Console.ReadLine().Split(' ').Select(uint.Parse).Concat(new uint[] { uint.MaxValue / 3 }).ToArray();
            uint bestCost = uint.MaxValue;

            for(int j=1;j<sizes.Length - 1; ++j)
            {
                int bestI = sizes.Length - 1;
                for(int i = 0; i < j; ++i)
                {
                    if (sizes[i] < sizes[j] && costs[i] < costs[bestI])
                    {
                        bestI = i;
                    }
                }
                int bestK = sizes.Length - 1;
                for(int k = j + 1; k < sizes.Length; ++k)
                {
                    if(sizes[k] > sizes[j] && costs[k] < costs[bestK])
                    {
                        bestK = k;
                    }
                }

                bestCost = Math.Min(bestCost, costs[bestI] + costs[j] + costs[bestK]);
            }
            Console.Write(bestCost > uint.MaxValue / 3 ? -1 : (int)bestCost);
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

public class CodeForces87
{
#if TEST
    // To set this go to Project -> Properties -> Build -> General -> Conditional compilation symbols: -> enter 'TEST' into text box.
    const bool testing = false;
#else
const bool testing = false;
#endif

    private static int Next()
    {
        int c;
        int res = 0;
        do
        {
            c = reader.Read();
            if (c == -1)
                return res;
        } while (c < '0' || c > '9');
        res = c - '0';
        while (true)
        {
            c = reader.Read();
            if (c < '0' || c > '9')
                return res;
            res *= 10;
            res += c - '0';
        }
    }
    private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
    private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);
    class Node : IComparable
    {
        public int Index { get; set; }
        public double Value { get; set; }
        public int CompareTo(object obj)
        {
            return this.Value.CompareTo(((Node)obj).Value);
        }
    }
    static void program(TextReader input)
     {
        //var s = reader.ReadLine().TrimEnd();
        var n = int.Parse(reader.ReadLine().TrimEnd());
        var s = reader.ReadLine().TrimEnd().Split(' ').Select(long.Parse).ToList();
        var c = reader.ReadLine().TrimEnd().Split(' ').Select(long.Parse).ToList();
        var price = new long[n];
        var min = new long[n];
        var last = new long[n];
        for (var i = 0; i < n; i++)
        {
            price[i] = long.MaxValue;
            min[i] = long.MaxValue;
            last[i] = long.MaxValue;
        }
        for(var j = 0; j < n; j++)
        {
            for(var i = 0; i < j; i++)
            {
                if(s[i] < s[j])
                {
                    price[j] = Math.Min(price[j], c[i] + c[j]);
                }
            }
        }

        for(var k = 0; k < n; k++)
        {
            for(var j = 0; j < k; j++)
            {
                if(price[j] != long.MaxValue && s[k] > s[j])
                {
                    last[k] = Math.Min(last[k], price[j] + c[k]);
                }
            }
        }
        var res = last.Min(); ;
        Console.WriteLine(res == long.MaxValue ? -1 : res);
    }

    public static void Main(string[] args)
    {
        CultureInfo nonInvariantCulture = new CultureInfo("en-US");
        Thread.CurrentThread.CurrentCulture = nonInvariantCulture;
        if (!testing)
        { // set testing to false when submiting to codeforces
            program(Console.In); // write your program in 'program' function (its your new main !)
            return;
        }

        Console.WriteLine("Test Case(1) => expected :");
        Console.WriteLine("3\n2\n4\n");
        Console.WriteLine("Test Case(1) => found    :");
        program(new StringReader("4 3\n2\n3\n4\n"));
        Console.WriteLine();

        Console.WriteLine("Test Case(2) => expected :");
        Console.WriteLine("13\n3\n8\n9\n");
        Console.WriteLine("Test Case(2) => found    :");
        program(new StringReader("13 4\n10\n5\n4\n8\n"));
        Console.WriteLine();

    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            int n = int.Parse(Console.ReadLine());
            int[] s = Console.ReadLine().Split().Select(r => int.Parse(r)).ToArray();
            int[] c = Console.ReadLine().Split().Select(r => int.Parse(r)).ToArray();
            var tlists = new List<List<int>>();
            for (int i = 0; i < n; i++) {
                //Console.Write(i + ": ");
                var l = new List<int>();
                for (int j = 0; j < i; j++) {
                    if (s[j] < s[i]) {
                        l.Add(j);
                        //Console.Write(j + " ");
                    }
                }
                tlists.Add(l);
                //Console.WriteLine();
            }
            int[] dp1 = new int[3003];
            for (int i = 0; i < n; i++) {
                int min = int.MaxValue;
                for (int j = 0; j < tlists[i].Count; j++) {
                    if (c[tlists[i][j]] < min)
                        min = c[tlists[i][j]];
                }
                dp1[i] = min;
                //Console.WriteLine(i + ": " + dp1[i]);
            }
            int[] dp2 = new int[3003];
            for (int j = 2; j < n; j++) {
                int[,] dp2i = new int[3003, 2];
                dp2i[1, 0] = int.MaxValue;
                dp2i[1, 1] = (tlists[j].Count > 1 ? (s[tlists[j][0]] < s[tlists[j][1]] ? c[tlists[j][0]] + c[tlists[j][1]] : int.MaxValue) : int.MaxValue);
                for (int i = 2; i < tlists[j].Count; i++) {
                    dp2i[i, 0] = Math.Min(dp2i[i - 1, 1], dp2i[i - 1, 0]);
                    dp2i[i, 1] = (dp1[tlists[j][i]] != int.MaxValue ? dp1[tlists[j][i]] + c[tlists[j][i]] : int.MaxValue);
                }
                dp2[j] = tlists[j].Count > 1 ? Math.Min(dp2i[tlists[j].Count - 1, 0], dp2i[tlists[j].Count - 1, 1]) : int.MaxValue;
                //Console.WriteLine(j + ": " + dp2[j]);
            }
            int[,] dp3 = new int[3003, 2];
            dp3[2, 0] = int.MaxValue;
            dp3[2, 1] = s[0] < s[1] && s[1] < s[2] ? c[0] + c[1] + c[2] : int.MaxValue;
            for (int i = 3; i < n; i++) {
                dp3[i, 0] = Math.Min(dp3[i - 1, 0], dp3[i - 1, 1]);
                dp3[i, 1] = (dp2[i] != int.MaxValue ? dp2[i] + c[i] : int.MaxValue);
            }
            int answer = Math.Min(dp3[n - 1, 0], dp3[n - 1, 1]);
            Console.WriteLine(answer != int.MaxValue ? answer : -1);
        }
    }
}


using System;
public class Program{
    public static void Main(){
        int n = int.Parse(Console.ReadLine());
        string[] ss = Console.ReadLine().Split(' ');
        string[] cs = Console.ReadLine().Split(' ');
        long[] s = new long[n];
        long[] c = new long[n];
        for(int i=0; i<n; i++){
            s[i]=long.Parse(ss[i]);
            c[i]=long.Parse(cs[i]);
        }
        long r=-1;
        long r1=-1;
        long r2=-1;
        for(int i=0; i<n; i++){
            if(r1!=-1&&r1<c[i])continue;
            for(int j=i+1; j<n; j++){
                if((r2!=-1&&r2<c[i]+c[j])||s[i]>=s[j])continue;
                for(int k=j+1; k<n; k++){
                    if(s[j]>=s[k])continue;
                    if(r==-1||r>c[i]+c[j]+c[k]){
                        r1=c[i];
                        r2=c[i]+c[j];
                        r=c[i]+c[j]+c[k];
                    }
                }
            }
        }
        Console.WriteLine(r);
    }
}


using System;
public class Program{
    public static void Main(){
        int n = int.Parse(Console.ReadLine());
        string[] ss = Console.ReadLine().Split(' ');
        string[] cs = Console.ReadLine().Split(' ');
        long[] s = new long[n];
        long[] c = new long[n];
        for(int i=0; i<n; i++){
            s[i]=long.Parse(ss[i]);
            c[i]=long.Parse(cs[i]);
        }
        long r=-1;
        for(int j=1; j<n-1; j++){
            long leftmin=-1;
            for(int i=0; i<j; i++){
                if(s[i]<s[j]&&(leftmin==-1||leftmin>c[i]))leftmin=c[i];
            }
            if(leftmin==-1)continue;
            long rightmin=-1;
            for(int k=j+1; k<n; k++){
                if(s[j]<s[k]&&(rightmin==-1||rightmin>c[k]))rightmin=c[k];
            }
            if(rightmin==-1)continue;
            if(r==-1||r>leftmin+c[j]+rightmin)r=leftmin+c[j]+rightmin;
        }
        Console.WriteLine(r);
    }
}


use std::io;
use std::cmp;

fn main(){
    let mut input_string = String::new();
    io::stdin().read_line(&mut input_string).unwrap();
    let n: u32 = input_string.trim().parse().unwrap();
    let fonts = read_vector(&io::stdin());
    let costs = read_vector(&io::stdin());
    let mut two_costs: Vec<i64> = Vec::with_capacity(fonts.len());
    let mut three_costs: Vec<i64> = Vec::with_capacity(fonts.len());
    for pos in 0..fonts.len() {
        // -1 denotes impossibility
        let mut cost = -1;
        for sec in (pos + 1)..fonts.len() {
            if fonts[sec] > fonts[pos] {
                if cost == -1{
                    cost = costs[sec] + costs[pos];
                }
                else{
                    cost = cmp::min(cost, costs[sec] + costs[pos]);
                }
            }
        }
        two_costs.push(cost);
    }

    for pos in 0..fonts.len(){
        // -1 denotes impossibility
        let mut cost = -1;
        for sec in (pos + 1)..fonts.len(){
            if two_costs[sec] != -1 && (fonts[sec] > fonts[pos]) {
                if cost == -1{
                    cost = costs[pos] + two_costs[sec];
                }
                else{
                    cost = cmp::min(cost, costs[pos] + two_costs[sec]);
                }
            }
        }
        three_costs.push(cost);
    }
    let mut mini = -1;
    for pos in 0..three_costs.len(){
        if three_costs[pos] != -1{
            if mini == -1{
                mini = three_costs[pos];
            }
            else{
                mini = cmp::min(mini, three_costs[pos]);
            }
        }
    }
    println!("{}", mini);
}

pub fn read_vector(stdin: &io::Stdin) -> Vec<i64> {
    let mut s = String::new();
    stdin.read_line(&mut s).expect("Failed to read input");
    s = s.trim().to_string();
    let mut v: Vec<i64> = Vec::new();
    for n in s.split_whitespace() {
        let i: i64 = n.parse().expect("Input a valid number");
        v.push(i);
    }
    v
}


fn main() {
    let mut input = String::new();
    use std::io::{self, prelude::*};
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();
    let s: Vec<u64> = it.by_ref().take(n).map(|x| x.parse().unwrap()).collect();
    let c: Vec<u64> = it.by_ref().take(n).map(|x| x.parse().unwrap()).collect();

    let mut gll: Vec<Vec<_>> = (0..n).map(|i| {
        (i + 1..n).filter(|&j| s[i] < s[j]).collect()
    }).collect();

    for gl in gll.iter_mut() {
        gl.sort_unstable_by_key(|&i| c[i]);
    }

    let mut ans = None;

    for i in 0..n {
        for &j in gll[i].iter() {
            match gll[j].first() {
                Some(&k) => {
                    let c = c[i] + c[j] + c[k];
                    match ans {
                        Some(cur) if cur <= c => (),
                        _ => ans = Some(c),
                    }
                }
                None => (),
            }
        }
    }

    match ans {
        Some(c) => println!("{}", c),
        None => println!("-1"),
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    let n = n.trim().parse().unwrap();
    for i in 0..n
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.1);
    let mut out = -1i64;
    let pirce = pairs.as_slice();
    for i in 0..pirce.len()
    {
        let num = dfs(pirce.split_at(i).1, 0, 0, &pirce[i]);
        if out == -1
        {
            out = num;
        }
        else if num != -1
        {
            out = if out < num {out} else {num};
        }
    }

    println!("{}", out);
}

fn cmp(a: &(i64, i64, i32), b: &(i64, i64, i32), turn: &(i64, i64, i32)) -> bool
{
    if ((a.0 > b.0 && a.2 > b.2) || (a.0 < b.0 && a.2 < b.2)) && ((a.0 > turn.0 && a.2 > turn.2) || (a.0 < turn.0 && a.2 < turn.2))
    {
        true
    }
    else
    {
        false
    }
}

fn dfs(pairs: &[(i64, i64, i32)], cnt: i32, sum: i64, turn: &(i64, i64, i32)) -> i64
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        let mut part = pairs.split_at(1).1;
        while !part.is_empty()
        {
            if cmp(&part[0], &pairs[0], turn)
            {
                let num = dfs(pirce.split_at(i).1, 0, 0, &pirce[i]);
                if out == -1
                {
                    out = num;
                }
                else if num != -1
                {
                    out = if out < num {out} else {num};
                }
            }
            part = part.split_at(1).1;
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    for i in 0..n.trim().parse().unwrap()
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.0);
    let mut out = -1i64;
    let pirce = pairs.as_slice();
    for i in 0..(pirce.len() - 2)
    {
        let num = dfs(pirce.split_at(i).1, 0, 0);
        out = min(out, num);
    }

    println!("{}", out);
}

fn min(out: i64, num: i64) -> i64
{
    if num != -1
    {
        if out == -1
        {
            num
        }
        else
        {
            if num < out {num} else {out}
        }
    }
    else
    {
        out
    }
}

fn dfs(pairs: &[(i64, i64, i32)], cnt: i32, sum: i64) -> i64
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        let mut part = pairs.split_at(1).1;
        while let Some(&value) = part.first()
        {
            if value.0 > pairs[0].0 && value.2 > pairs[0].2
            {
                let num = dfs(part, cnt + 1, sum + pairs[0].1);
                out = min(out, num);
            }
            part = part.split_at(1).1;
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    let n = n.trim().parse().unwrap();
    for i in 0..n
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.1);
    let mut out = -1i64;
    let pirce = pairs.as_slice();
    for i in 0..pirce.len()
    {
        if out == -1
        {
            out = dfs(pirce.split_at(i).1, 0, 0, &pirce[i]);
        }
        else
        {
            break;
        }
    }

    println!("{}", out);
}

fn cmp(a: &(i64, i64, i32), b: &(i64, i64, i32), turn: &(i64, i64, i32)) -> bool
{
    if ((a.0 > b.0 && a.2 > b.2) || (a.0 < b.0 && a.2 < b.2)) && ((a.0 > turn.0 && a.2 > turn.2) || (a.0 < turn.0 && a.2 < turn.2))
    {
        true
    }
    else
    {
        false
    }
}

fn dfs(pairs: &[(i64, i64, i32)], cnt: i32, sum: i64, turn: &(i64, i64, i32)) -> i64
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        let mut part = pairs.split_at(1).1;
        while !part.is_empty()
        {
            if cmp(&part[0], &pairs[0], turn)
            {
                println!("{:?} {:?}", pairs[0], part[0]);
                out = dfs(part, cnt + 1, sum + pairs[0].1, turn);
                if out != -1
                {
                    break;
                }
            }
            part = part.split_at(1).1;
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    for i in 0..n.trim().parse().unwrap()
    {
        pairs.push((displays[i].parse::<i32>().unwrap(), sizes[i].parse::<i32>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.0);

    println!("{}", dfs(pairs.as_slice(), 0, 0));
}

fn dfs(pairs: &[(i32, i32, i32)], cnt: i32, sum: i32) -> i32
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i32;
        for i in 0..pairs.len()
        {
            let mut part = pairs.split_at(i + 1).1;
            while let Some(&value) = part.first()
            {
                if value.0 > pairs[i].0 && value.2 > pairs[i].2
                {
                    let num = dfs(part, cnt + 1, sum + pairs[i].1);
                    if num != -1
                    {
                        if out == -1
                        {
                            out = num;
                        }
                        else
                        {
                            out = if num < out {num} else {out};
                        }
                    }
                }
                part = part.split_at(1).1;
            }
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    for i in 0..n.trim().parse().unwrap()
    {
        pairs.push((displays[i].parse::<i32>().unwrap(), sizes[i].parse::<i32>().unwrap()));
    }
    pairs.sort_by(|a, b| if a.0 != b.0 {a.0.cmp(&b.0)} else {a.1.cmp(&b.1)});

    println!("{}", dfs(pairs.as_slice(), 0, 0));
}

fn dfs(pairs: &[(i32, i32)], cnt: i32, sum: i32) -> i32
{
    if cnt == 3
    {
        sum
    }
    else if pairs.is_empty()
    {
        -1
    }
    else
    {
        let mut out = -1i32;
        for i in 0..pairs.len()
        {
            let mut part = pairs.split_at(i + 1).1;

            while let Some(&value) = part.first()
            {
                if value.0 > pairs[i].0
                {
                    let num = dfs(part, cnt + 1, sum + pairs[i].1);
                    if num != -1
                    {
                        if out == -1
                        {
                            out = num;
                        }
                        else
                        {
                            out = if num < out {num} else {out};
                        }
                    }
                }
                part = part.split_at(1).1;
            }
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    let n = n.trim().parse().unwrap();
    for i in 0..n
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.1);
    let mut out = -1i64;
    let pirce = pairs.as_mut_slice();
    for i in 0..pirce.len()
    {
        if pirce[i].2 == -1
        {
            continue;
        }
        let turn = pirce[i];
        let num = dfs(pirce.split_at_mut(i).1, 0, 0, turn);
        if out == -1
        {
            out = num;
        }
        else if num != -1
        {
            out = if out < num {out} else {num};
        }
    }

    println!("{}", out);
}

fn cmp(a: &(i64, i64, i32), b: &(i64, i64, i32), turn: &(i64, i64, i32)) -> bool
{
    if ((a.0 > b.0 && a.2 > b.2) || (a.0 < b.0 && a.2 < b.2)) && ((a.0 > turn.0 && a.2 > turn.2) || (a.0 < turn.0 && a.2 < turn.2))
    {
        true
    }
    else
    {
        false
    }
}

fn dfs(pairs: &mut [(i64, i64, i32)], cnt: i32, sum: i64, turn: (i64, i64, i32)) -> i64
{
    if cnt == 2
    {
        pairs[0].2 = -1;
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        for i in 1..pairs.len()
        {
            if pairs[i].2 != -1 && cmp(&pairs[i], &pairs[0], &turn)
            {
                let new = pairs[0].1;
                let num = dfs(pairs.split_at_mut(i).1, cnt + 1, sum + new, turn);
                if out == -1
                {
                    out = num;
                }
                else if num != -1
                {
                    out = if out < num {out} else {num};
                }
            }
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    let n = n.trim().parse().unwrap();
    for i in 0..n
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.1);
    let mut out = -1i64;
    let pirce = pairs.as_slice();
    for i in 0..pirce.len()
    {
        let num = dfs(pirce.split_at(i).1, 0, 0, &pirce[i]);
        if out == -1
        {
            out = num;
        }
        else if num != -1
        {
            out = if out < num {out} else {num};
        }
    }

    println!("{}", out);
}

fn cmp(a: &(i64, i64, i32), b: &(i64, i64, i32), turn: &(i64, i64, i32)) -> bool
{
    if ((a.0 > b.0 && a.2 > b.2) || (a.0 < b.0 && a.2 < b.2)) && ((a.0 > turn.0 && a.2 > turn.2) || (a.0 < turn.0 && a.2 < turn.2))
    {
        true
    }
    else
    {
        false
    }
}

fn dfs(pairs: &[(i64, i64, i32)], cnt: i32, sum: i64, turn: &(i64, i64, i32)) -> i64
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        let mut part = pairs.split_at(1).1;
        while !part.is_empty()
        {
            if cmp(&part[0], &pairs[0], turn)
            {
                out = dfs(part, cnt + 1, sum + pairs[0].1, turn);
                if out != -1
                {
                    break;
                }
            }
            part = part.split_at(1).1;
        }
        out
    }
}


use std::io;

fn main()
{
    let mut n = String::new();
    let mut line1 = String::new();
    let mut line2 = String::new();

    io::stdin().read_line(&mut n).unwrap();
    io::stdin().read_line(&mut line1).unwrap();
    io::stdin().read_line(&mut line2).unwrap();
    let displays: Vec<&str> = line1.trim().split_whitespace().collect();
    let sizes: Vec<&str> = line2.trim().split_whitespace().collect();
    let mut pairs = Vec::new();
    let n = n.trim().parse().unwrap();
    for i in 0..n
    {
        pairs.push((displays[i].parse::<i64>().unwrap(), sizes[i].parse::<i64>().unwrap(), i as i32));
    }
    pairs.sort_by_key(|k| k.1);
    let mut out = -1i64;
    let pirce = pairs.as_slice();
    for i in 0..pirce.len()
    {
        let num = dfs(pirce.split_at(i).1, 0, 0, &pirce[i]);
        if out == -1
        {
            out = num;
        }
        else if num != -1
        {
            out = if out < num {out} else {num};
        }
    }

    println!("{}", out);
}

fn cmp(a: &(i64, i64, i32), b: &(i64, i64, i32), turn: &(i64, i64, i32)) -> bool
{
    if ((a.0 > b.0 && a.2 > b.2) || (a.0 < b.0 && a.2 < b.2)) && ((a.0 > turn.0 && a.2 > turn.2) || (a.0 < turn.0 && a.2 < turn.2))
    {
        true
    }
    else
    {
        false
    }
}

fn dfs(pairs: &[(i64, i64, i32)], cnt: i32, sum: i64, turn: &(i64, i64, i32)) -> i64
{
    if cnt == 2
    {
        sum + pairs[0].1
    }
    else
    {
        let mut out = -1i64;
        let mut part = pairs.split_at(1).1;
        while !part.is_empty()
        {
            if cmp(&part[0], &pairs[0], turn)
            {
                let num = dfs(part, cnt + 1, sum + pairs[0].1, turn);
                if out == -1
                {
                    out = num;
                }
                else if num != -1
                {
                    out = if out < num {out} else {num};
                }
            }
            part = part.split_at(1).1;
        }
        out
    }
}