fn is_kadomatsu((a, b, c): (isize, isize, isize)) -> bool { if a == b || b == c || c == a { return false; } (a.min(b).min(c) == b) || (a.max(b).max(c) == b) } fn solve() -> isize { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let mut a = String::new(); std::io::stdin().read_line(&mut a).ok(); let a: Vec = a.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut result = 0isize; for start in 0..3 { let mut dp = vec![vec![0isize; 2]; n+1]; for i in start..n+start-2 { let vals = (a[i], a[(i+1)%n], a[(i+2)%n]); dp[i][0] = if i == 0 { 0 } else if i < 3 { dp[i-1][0] } else { dp[i-1][0].max(dp[i-3][1]) }; dp[i][1] = if i == 0 { 0 } else if i < 3 { dp[i-1][0] } else { dp[i-1][0].max(dp[i-3][1]) }; dp[i][1] += if is_kadomatsu(vals) { a[i] } else { 0 }; } result = result.max(dp.iter().map(|v| *v.iter().max().unwrap()).max().unwrap()); } result } fn main() { let mut t = String::new(); std::io::stdin().read_line(&mut t).ok(); let t: usize = t.trim().parse().unwrap(); let mut result = Vec::with_capacity(t); for _ in 0..t { result.push(solve()); } for &v in result.iter() { println!("{}", v); } }