Algorithm for memory allocation