n = int(input()) from collections import defaultdict group = defaultdict(int) for _ in range(n): s = input().strip() if not s: continue # Check if the string is good good = True prev = s[0] for c in s[1:]: if c < prev: good = False break prev = c if not good: continue a = s[0] b = s[-1] length = len(s) key = (a, b) if group[key] < length: group[key] = length # Convert grouped items into tuples (a, b, length) with a and b as integers tuples = [] for (a_char, b_char), length in group.items(): a = ord(a_char) - ord('a') b = ord(b_char) - ord('a') tuples.append((a, b, length)) # Sort the tuples by a ascending, then by length descending, then by b ascending tuples.sort(key=lambda x: (x[0], -x[2], x[1])) dp = [0] * 26 prefix_max = [0] * 26 for a, b, length in tuples: current_max_prev = prefix_max[a] new_value = current_max_prev + length if new_value > dp[b]: dp[b] = new_value # Update the prefix_max array new_prefix = [0] * 26 new_prefix[0] = dp[0] for i in range(1, 26): new_prefix[i] = max(new_prefix[i-1], dp[i]) prefix_max = new_prefix print(max(dp))