$n = gets.to_i - 1 $v = gets.split.map(&:to_i) def dfs(n, memo) return $v[0] if n==0 return $v[1] if n==1 tmp = -1 (n-2).downto(0) do |i| tmp = [tmp, (memo[i] < 0 ? dfs(i, memo) : memo[i]) ].max end memo[n] = tmp + $v[n] return memo[n] end puts dfs($n, Array.new($n+1, -1))