An optimal algorithm for the maximum alignment of terminals