Is this like wordwrapping? Here's an approach I've used ...
There leaves out some details ... what if a single
word is longer than max? And get rid of that extra blank I put at the front of each line.
An alternate algorithm that does fewer loops ...
I never used that one because I had to remove redundant spaces between words and put two spaces after sentences like old timey typists.
Was that the right problem?