The PM tends to be the leader of the group most likely to form a stable government. Generally a party leader who was elected by their party to the role. The public does not elect the PM directly and neither do they vote for a party. They vote for a representative for their area, although many voters consider which party, if applicable, candidates have joined when they make a choice. Note that the PM need not be the leader of the largest party in the Commons: it is possible that a coalition of smaller parties may result in an overall majority power that appears to be a more stable choice. Basically the monarch chooses who to ask to form a government.