
fun main(args : Array<String>) {
    val N = readLine()!!.toInt()
    val A = readLine()!!.split(" ").map { it.toLong() }.toMutableList()
    prefixSum2(A)

    var min = Long.MAX_VALUE

    var partitionPositionForL = 0
    var partitionPositionForR = 2

    fun LMeetsConditionOnNext(partionPosition: Int, center: Int) : Boolean {
        val current = partionPosition
        val currentLeftSum = A.get(current)
        val currentRightSum = A.get(center - 1) - A.get(current)
        val currentDiff = Math.abs(currentLeftSum - currentRightSum)

        val next = partionPosition + 1
        val nextLeftSum = A.get(next)
        val nextRightSum = A.get(center - 1) - A.get(next)
        val nextDiff = Math.abs(nextLeftSum - nextRightSum)

        return nextDiff < currentDiff
    }

    fun RMeetsConditionOnNext(partionPosition: Int, center: Int) : Boolean {
        val current = partionPosition
        val currentLeftSum = A.get(current) - A.get(center - 1)
        val currentRightSum = A.get(N - 1) - A.get(current)
        val currentDiff = Math.abs(currentLeftSum - currentRightSum)

        val next = partionPosition + 1
        val nextLeftSum = A.get(next) - A.get(center - 1)
        val nextRightSum = A.get(N - 1) - A.get(next)
        val nextDiff = Math.abs(nextLeftSum - nextRightSum)

        return nextDiff < currentDiff
    }

    for (center in 2..N-2) {
        //val L = A.subList(0, center)
        //val R = A.subList(center, N)
        // Find the optimized partition for L
        while (partitionPositionForL < center - 1 && LMeetsConditionOnNext(partitionPositionForL, center)) {
            partitionPositionForL++
        }

        // Find the optimized partition for L
        while (partitionPositionForR < N - 1 && RMeetsConditionOnNext(partitionPositionForR, center)) {
            partitionPositionForR++
        }

        val sumP = A.get(partitionPositionForL)
        val sumQ = A.get(center - 1) - A.get(partitionPositionForL)
        val sumR = A.get(partitionPositionForR) - A.get(center - 1)
        val sumS = A.get(N - 1) - A.get(partitionPositionForR)
        val list = listOf<Long>(sumP, sumQ, sumR, sumS).toMutableList()
        list.sort()
        val result = list.last() - list.first()
        min = Math.min(min, result)


        // PREPARE FOR INCREMENTING CENTER
        if (center == partitionPositionForR) {
            partitionPositionForR++
        }
    }

    println(min)
}

fun prefixSum2(A: MutableList<Long>) {
    for(i in 1..(A.size - 1)) {
        A.set(i, A.get(i) + A.get(i - 1))
    }
}
