Longest length algorithm