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