"Tetris" Optimization

Do you want to solve the problem to understand it better or do you “just” need something that nests the rectangles within a shape?

For the latter there are several plug-ins that achieve exactly that eg https://www.food4rhino.com/en/app/opennest

It comes up regularly with CNC or laser cutting, the term you want to search for is “nesting” or “packing”