using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
using StringBuilder = System.Text.StringBuilder;
using System.Numerics;
namespace Program
{
public class Solver
{
///
/// O(N^3) Naive TLE
///
public void Solve()
{
var n = sc.Integer();
var a = sc.Integer(n);
var S = a.Distinct().ToList();
S.Add(-1); S.Add(int.MaxValue);
S.Sort();
for (int i = 0; i < n; i++)
a[i] = S.BinarySearch(a[i]);
var sz = S.Count;
var dp = new int[sz, sz];
for (int i = 0; i < sz; i++)
for (int j = 0; j < sz; j++)
dp[i, j] = -10000000;
dp[0, sz - 1] = dp[sz - 1, 0] = 0;
foreach (var i in a)
{
for (int j = 0; j < sz; j++)
for (int k = 0; k < sz; k++)
{
if (j == i || k == i)
continue;
if (dp[j,k] < 0) continue;
if ((j < k && k > i) || (j > k && k < i))
dp[k, i] = Math.Max(dp[k, i], dp[j, k] + 1);
}
}
var max = 0;
for (int i = 0; i < sz; i++)
for (int j = 0; j < sz; j++)
max = Math.Max(max, dp[i, j]);
if (max<3) max = 0;
IO.Printer.Out.WriteLine(max);
}
public IO.StreamScanner sc = new IO.StreamScanner(Console.OpenStandardInput());
static T[] Enumerate(int n, Func f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; }
static public void Swap(ref T a, ref T b) { var tmp = a; a = b; b = tmp; }
}
}
#region main
static class Ex
{
static public string AsString(this IEnumerable ie) { return new string(System.Linq.Enumerable.ToArray(ie)); }
static public string AsJoinedString(this IEnumerable ie, string st = " ") { return string.Join(st, ie); }
static public void Main()
{
var solver = new Program.Solver();
solver.Solve();
Program.IO.Printer.Out.Flush();
}
}
#endregion
#region Ex
namespace Program.IO
{
using System.IO;
using System.Text;
using System.Globalization;
public class Printer : StreamWriter
{
static Printer() { Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false }; }
public static Printer Out { get; set; }
public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
public Printer(System.IO.Stream stream) : base(stream, new UTF8Encoding(false, true)) { }
public Printer(System.IO.Stream stream, Encoding encoding) : base(stream, encoding) { }
public void Write(string format, T[] source) { base.Write(format, source.OfType