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 Ruby (2.3.3) (judge verdict: Accepted)

def main
  nums_cnt = ARGF.gets.chomp.to_i
  nums = ARGF.gets.split.map(&:to_i)

  # 累積和
  s = 0
  accum_ary = nums.map do |n|
    s += n
    s
  end
  # pp accum_ary

  min_diff = nil

  # 2番目（真ん中）の区切りを決める
  # m_idx=2 の場合、2の前が区切り という意味
  l = 1
  r = 3
  2.upto(nums.length-2) do |m_idx|
    # しゃくとり法
    l_side_sum = accum_ary[m_idx-1] # left側の合計

    side_min_diff = nil
    ll_sum = lr_sum = 0
    # 左サイドの分割位置
    l.upto(m_idx-1) do |i|
      ll = accum_ary[i-1]
      lr = l_side_sum - ll
      diff = (ll - lr).abs
      if side_min_diff.nil? || diff < side_min_diff
        ll_sum, lr_sum = ll, lr
        side_min_diff = diff
        l = i
      else
        # 更新しなかった＝右端が行き過ぎた！
        break
      end
    end

    # しゃくとり法
    r_side_sum = accum_ary[-1] - l_side_sum # right側の合計

    side_min_diff = nil
    rl_sum = rr_sum = 0
    # 右サイドの分割位置
    r.upto(nums.length-1) do |i|
      rl = accum_ary[i-1] - l_side_sum
      rr = r_side_sum - rl
      diff = (rl - rr).abs
      if side_min_diff.nil? || diff < side_min_diff
        rl_sum, rr_sum = rl, rr
        side_min_diff = diff
        r = i
      else
        # 更新しなかった＝右端が行き過ぎた！
        break
      end
    end

    min, max = [ll_sum, lr_sum, rl_sum, rr_sum].minmax
    diff = max - min
    min_diff = diff if min_diff.nil? || diff < min_diff
  end

  puts min_diff
end

if __FILE__ == $0
  main
end