def check(a) a.uniq.size == 3 && (a.max == a[1] || a.min == a[1]) end def func(n, a) dp = [0] * -~n (0..n).each do |i| dp[i] = [dp[i], dp[i - 1] || 0].max dp[i + 3] = [dp[i + 3], dp[i] + a[i]].max if check(a[i, 3]) end dp[n] end gets.to_i.times do n = gets.to_i a = gets.split.map(&:to_i) puts [func(n, a), func(n, a[1..] + a[0, 1]), func(n, a[2..] + a[0, 2])].max end