inputs = STDIN.readlines.map(&:chomp) N = inputs[0].to_i Vs = inputs[1].split(/\s+/).map(&:to_i) class Block def initialize(range, head_throughs, tail_throughs, max_value) @range = range @head_throughs = head_throughs @tail_throughs = tail_throughs @max_value = max_value end attr_reader :range, :head_throughs, :tail_throughs, :max_value end def merge(blocks1, blocks2) blocks1.product(blocks2).select { |block1, block2| throughs = block1.tail_throughs + block2.head_throughs 1 <= throughs && throughs <= 2 }.map { |block1, block2| Block.new( block1.range.first..block2.range.last, block1.head_throughs, block2.tail_throughs, block1.max_value + block2.max_value ) }.group_by { |block| [block.head_throughs, block.tail_throughs] }.map { |throughs, blocks| blocks.max_by(&:max_value) } end cands = Vs.map.with_index { |v, i| [Block.new(i..i, 0, 0, v), Block.new(i..i, 1, 1, 0)] } until cands.size == 1 cands = cands.each_slice(2).map { |blocks1, blocks2| if blocks2 merge(blocks1, blocks2) else blocks1 end } end puts cands.first.max_by(&:max_value).max_value