from collections.abc import Iterable def accum_dp1(xs: Iterable, f, op, e: int, size: int, init: Iterable, *, is_reset=True): dp = [e] * size for i, v in init: dp[i] = v for x in xs: pp = [e] * size if is_reset else dp.copy() dp, pp = pp, dp for i in range(size): for p, v in f(i, pp[i], x): if not (0 <= p < size): continue dp[p] = op(dp[p], v) return dp N = int(input()) SS = [input() for _ in range(N)] def is_ascendant(s: str) -> bool: p = 0 for c in map(ord, s): if p > c: return False p = c return True def conv(s: str): a = ord(s[0]) - ord('a') b = ord(s[-1]) - ord('a') return a, b, len(s) def f(i, v, x): a, b, n = x # (先頭文字, 末尾文字, 長さ) if i <= a: return [(b, v+n)] return [] def op(a, b): return max(a, b) ss = sorted([conv(s) for s in SS if is_ascendant(s)]) dp = accum_dp1(ss, f, op, 0, 26, [], is_reset=False) ans = max(dp) print(ans)