#include #define rep(i, n) for (int i = 0; i < (n); i++) using namespace std; using ll = long long; using P = pair; template void chmin(T& t, const U& u) { if (t > u) t = u; } template void chmax(T& t, const U& u) { if (t < u) t = u; } int main() { int n; cin >> n; vector s(n); rep(i, n) cin >> s[i]; vector> dist(26, vector(26)); vector plus(26); rep(i, n) { string t = s[i]; sort(t.begin(), t.end()); if (s[i] != t) continue; int m = s[i].size(); int start = *(s[i].begin()) - 'a'; int end = *(s[i].rbegin()) - 'a'; if (start == end) { chmax(plus[start], m); } else { for (int j = 0; j <= start; j++) { chmax(dist[j][end], m); } } } ll ans = 0; rep(i, 26) rep(j, 26) dist[i][j] += plus[i]; rep(k, 26) rep(i, 26) rep(j, 26) { if (i >= k || k >= j) continue; dist[i][j] = max(dist[i][j], dist[i][k] + dist[k][j]); chmax(ans, dist[i][j] + plus[j]); } cout << ans << endl; }