use std::collections::BTreeSet; use std::cmp; fn main() { let n: usize = { let mut buf = String::new(); std::io::stdin().read_line(&mut buf).unwrap(); buf.trim_end().parse().unwrap() }; let a: Vec = { let mut buf = String::new(); std::io::stdin().read_line(&mut buf).unwrap(); let iter = buf.split_whitespace(); iter.map(|x| x.parse().unwrap()).collect() }; let mut ans = std::usize::MAX; let mut left = BTreeSet::new(); let mut right = a.iter().cloned().collect::>(); left.insert(a[0]); right.remove(&a[0]); for i in 1..(n - 1) { right.remove(&a[i]); match left.range(a[i]..).next() { Some(x) => { match right.range(a[i]..).next() { Some(y) => { ans = cmp::min(ans, x + a[i] + y); }, None => (), } }, None => (), } match left.range(..a[i]).next() { Some(x) => { match right.range(..a[i]).next() { Some(y) => { ans = cmp::min(ans, x + a[i] + y); }, None => (), } }, None => (), } left.insert(a[i]); } if ans == std::usize::MAX { println!("-1"); } else { println!("{}", ans); } }