def f(a, b) _party = a.sort.map{|v| v * MOD} troop = b.map{|v| v / 2 * MOD} troop.size.times.inject(1.0/0){|r| party = _party.dup (troop.all?{|elv| lv_cnt = party.shift + elv + 1 if lv_cnt % MOD < r nth = party.bsearch_index{|v| v >= lv_cnt} || party.size party.insert(nth, lv_cnt) end } ? [r, party.map{|v| v % MOD}.max].min : r).tap{ troop.rotate! } } end N = gets.to_i A = gets.split.take(N).map(&:to_i) B = gets.split.take(N).map(&:to_i) MOD = 2000 p f(A, B)