Slightly better algorithm