def read_data $stdin.read.lines(chomp: true).drop(1) end def ok?(prev, value) if prev prev[-1] <= value[0] else true end end def solve(n, list, used, acc, max) if max.join.size < acc.join.size max = acc end list.each_with_index do |v, i| unless used[i] if ok?(acc.last, v) used[i] = true val = solve(n + 1, list, used, acc + [v], max) if max.join.size < val.join.size max = val end used[i] = false end end end max end def remove_error_data(list) list.find_all do |v| if v.size == 1 true else v.chars.each_cons(2).all? do |a, b| a.codepoints.first <= b.codepoints.first end end end end def main list = read_data valid_list = remove_error_data(list) pattern = solve(0, valid_list, [false] * valid_list.size, [], []) puts pattern.join.size end main