Endogenous population subgroups: the best population partition and optimal number of groups