optimal recursive building buying algorithm