def scan;gets.split.map(&:to_i);end @n,@m = scan @ww = scan @memo = {} def dfs(idx, lastflg, selected, firstflg) return firstflg&&lastflg ? @ww[0] : 0 if idx == @n key = [idx, lastflg, selected, firstflg] return @memo[key] if @memo[key] r = [] r << ((lastflg ? @ww[idx] : 0) + dfs(idx+1, true, selected+1, firstflg)) if selected < @m r << (dfs(idx+1, false, selected, firstflg)) if idx - selected < @n - @m return @memo[key] = r.max end if @n == @m p @ww.inject(:+) elsif @m <= 1 p 0 else p [dfs(1,false,0,false),dfs(1,true,1,true)].max end