Dynamic programming balanced partition