n, m = gets.split.map(&:to_i) ws = gets.split.map(&:to_i) memo = Array.new(2){ Array.new(2){ Array.new(2){ Array.new(m+1, -Float::INFINITY) } } } memo[0][0][0][m] = 0 memo[0][1][1][m-1] = 0 0.upto(n-2){|i| 0.upto(m){|j| memo[1][0][0][j] = [memo[0][0][0][j], memo[0][0][1][j]].max memo[1][0][1][j] = [memo[0][0][0][j+1], memo[0][0][1][j+1] + ws[i]].max if j < m memo[1][1][0][j] = [memo[0][1][0][j], memo[0][1][1][j]].max memo[1][1][1][j] = [memo[0][1][0][j+1], memo[0][1][1][j+1] + ws[i]].max if j < m } memo[0] = memo[1] memo[1] = Array.new(2){ Array.new(2){ Array.new(m+1, -Float::INFINITY) } } } memo[0][1][1][0] += ws.last puts [memo[0][0][0][0], memo[0][0][1][0], memo[0][1][0][0], memo[0][1][1][0]].max