# t(pi) from the definition of Ahmed and Snevily.
# t(pi) is the sum over all subsequences tau of length >= 3 of the number of runs of tau.
# A run is a maximal increasing or maximal decreasing block of adjacent entries.
import itertools, sys
def runs(seq):
    # The number of increasing runs plus the number of decreasing runs. A run has length >= 2.
    inc = dec = 0; prev = None
    for a, b in zip(seq, seq[1:]):
        d = 'u' if b > a else 'd'
        if d != prev:
            if d == 'u': inc += 1
            else: dec += 1
        prev = d
    return inc + dec
def t(pi):
    n = len(pi); tot = 0
    for mask in range(1 << n):
        if bin(mask).count('1') >= 3:
            tot += runs([pi[i] for i in range(n) if mask >> i & 1])
    return tot
if __name__ == '__main__':
    known = [2, 11, 37, 106, 270, 653, 1523]
    for n in range(3, 10):
        best = max(t(p) for p in itertools.permutations(range(1, n + 1)))
        print(n, best, 'known', known[n - 3], 'OK' if best == known[n - 3] else 'MISMATCH', flush=True)
