Problem:
Score : 600 points

Problem Statement

Snuke has an integer sequence A of length N.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E.
The positions of the cuts can be freely chosen.

Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Constraints

4 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.
Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2.
We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

#![allow(unused)]

use std::{cell, cmp, collections, fmt, io, iter, ops, str};

use cell::{Cell, RefCell};
use cmp::Ordering::{Equal, Greater, Less};
use collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use io::{Read, Write};

#[cfg(feature = "debug")]
macro_rules! debug {
    ($($args: tt)*) => { eprint!($($args)*) };
}

#[cfg(feature = "debug")]
macro_rules! debugln {
    ($($args: tt)*) => { eprintln!($($args)*) };
}

#[cfg(not(feature = "debug"))]
macro_rules! debug {
    ($($args:tt)*) => {};
}

#[cfg(not(feature = "debug"))]
macro_rules! debugln {
    ($($args:tt)*) => {};
}

macro_rules! vmax {
    ($x: expr, $y: expr) => { cmp::max($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::max($x, vmax!($($args),*)) };
}

macro_rules! vmin {
    ($x: expr, $y: expr) => { cmp::min($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::min($x, vmin!($($args),*)) };
}

fn main() {
    let n = parse_line::<usize>();
    let a = parse_vec::<i32>();

    let (sep_m, sum_l, sum_r) = separate_equal(&a);
    debugln!("dbg: {}, {}, {}", sep_m, sum_l, sum_r);

    let ans = ((sep_m - 1)..(sep_m + 1 + 1))
        .map(|sep_m| {
            let (sep_l, sum_ll, sum_lr) = separate_equal(&a[..sep_m]);
            debugln!("dbg: {}, {}, {}", sep_l, sum_ll, sum_lr);

            let (sep_r, sum_rl, sum_rr) = separate_equal(&a[sep_m..]);
            debugln!("dbg: {}, {}, {}", sep_r, sum_rl, sum_rr);

            let mut sums = [sum_ll, sum_lr, sum_rl, sum_rr];
            sums.sort();
            debugln!("{:?}", sums);
            sums[3] - sums[0]
        })
        .min()
        .unwrap();

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

fn separate_equal(a: &[i32]) -> (usize, i32, i32) {
    let (mut left, mut right) = (0, a.len());

    let slice_sum = |slice: &[i32]| slice.iter().sum::<i32>();

    let sum_diff = |idx| {
        let sum_l = slice_sum(&a[..idx]);
        let sum_r = slice_sum(&a[idx..]);
        (sum_l - sum_r).abs()
    };

    loop {
        let l = (left * 2 + right) / 3;
        let r = (left + right * 2) / 3;

        if sum_diff(l) < sum_diff(r) {
            if right == r {
                break;
            } else {
                right = r;
            }
        } else {
            if left == l {
                break;
            } else {
                left = l;
            }
        }
    }

    (left..(right + 1))
        .map(|i| (i, slice_sum(&a[..i]), slice_sum(&a[i..])))
        .min_by_key(|&(_, sum_l, sum_r)| (sum_l - sum_r).abs())
        .unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        //
    }
}

fn read_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.trim().to_owned()
}

fn read_word() -> String {
    const CAPACITY: usize = 16;

    let mut stdin = io::stdin();
    let mut byte: [u8; 1] = [0];

    loop {
        let mut buf = Vec::with_capacity(CAPACITY);

        loop {
            let res = stdin.read(&mut byte);

            if res.unwrap_or(0) == 0 || byte[0] <= b' ' {
                break;
            } else {
                buf.push(byte[0]);
            }
        }

        if !buf.is_empty() {
            return String::from_utf8(buf).unwrap();
        }
    }
}

fn parse_line<T: str::FromStr>() -> T {
    read_line().parse().ok().unwrap()
}

fn parse_word<T: str::FromStr>() -> T {
    read_word().parse().ok().unwrap()
}

fn parse_vec<T: str::FromStr>() -> Vec<T> {
    read_line()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn flush() {
    io::stdout().flush();
}

fn next_prime(x: i32) -> i32 {
    for i in (x + 1).. {
        if is_prime(i) {
            return i;
        }
    }

    panic!("attempt to add with overflow");
}

fn is_prime(x: i32) -> bool {
    let ceil = f64::from(x).sqrt().ceil() as i32;
    x == 2 || (2..(ceil + 1)).all(|i| x % i != 0)
}