N:= 15: # for terms before the first term >= 3^(N+1)
db:= proc(n) option remember; local L, d, m;
L:= convert(n, base, 3);
d:= nops(L);
d mod 3 = 0 and 3*numboccur(0, L) = d and 3*numboccur(1, L) = d
end proc:
W:= Vector(3^(N+1), datatype=integer[4]):
for d from 3 to N by 3 do
for t from 3^(d-1) to 3^d-1 do
if db(t) then
J:= [seq(i, i=t..3^(N+1), t)];
W[J]:= W[J] +~ 1;
fi
od od:
M:= max(W):
V:= Array(0..M): count:= 0:
for i from 1 to 3^(N+1) while count < M+1 do
if V[W[i]] = 0 then V[W[i]]:= i; count:= count+1 fi;
od:
L:= convert(V, list):
if not member(0, L, 'm') then m:= M+2 fi: