#include #define rep(i,n) for (int i=0; i < (n); i++) using namespace std; using ll = long long; int ctoi(char x){ return x - 'a'; } int main(){ ios::sync_with_stdio(false); int N; cin>>N; vector pos; rep(i,N){ string s; cin>>s; string t=s; sort(s.begin(), s.end()); if(s==t) pos.push_back(s); } for(string x:pos){ cerr << x << endl; } vector> moji(26,vector(26,0)); for(string x:pos){ int l=ctoi(x[0]), r=ctoi(x[x.size()-1]); int len=x.size(); moji[l][r]=max(moji[l][r], len); } rep(i,26){ rep(j,26){ cerr << moji[i][j] << " "; }cerr << endl; } cerr << "-------------------" << endl; int ans=0; vector dp(26,0); for(int r=0; r<26; r++){ for(int l=0; l<=r; l++){ if(r==l) dp[r] = max(dp[r],moji[r][r]); if(r>0 && r!=l){ dp[r] = max(dp[r], dp[l]+moji[l][r]+moji[r][r]); } } // dp[r] += moji[r][r]; ans = max(ans,dp[r]); } rep(i,26){ cerr << dp[i] << " "; }cerr << endl; cout << ans << endl; }