Praise be to Allah, and peace and blessings be upon the Messenger of Allah and his family.
Firstly:
If the imam gets up for a fifth rak‘ah by mistake, those who are praying behind him should alert him to that. If he does not sit back down, then the one who is praying behind him should sit and recite the tashahhud. Then he may say salaam and leave the imam, or he may wait for him during the tashahhud so that he can say the salaam with him.
This has been explained previously in the answer to question no. 98453 .
Secondly:
The scholars are unanimously agreed that the worshipper who catches up with the first rak‘ah with the imam and is going to say the salaam at the end of the prayer with him must follow the imam in doing the prostration of forgetfulness, whether the imam does that prostration before or after the salaam at the end of the prayer, and whether the imam alone got confused and made a mistake or the one who was praying behind him got confused too.
This is indicated by the words of the Prophet (blessings and peace of Allah be upon him): “The imam has only been appointed to be followed, so do not differ from him… And when he prostrates, then prostrate.” Agreed upon. The general meaning of these words includes the prostration of forgetfulness, so when the imam prostrates, the one who is praying behind him must follow him in prostrating.
Ibn Qudaamah (may Allah have mercy on him) said in al-Mughni:
If the imam makes a mistake, the one who is praying behind him must follow him in doing the prostration of forgetfulness whether he got confused along with the imam or only the imam got confused and made the mistake.
Ibn al-Mundhir said: All of the scholars from whom we acquired knowledge were unanimously agreed on that.
Ishaaq mentioned that this is in accordance with the consensus of the scholars, regardless of whether the prostration comes before or after the salaam, because the Messenger of Allah (blessings and peace of Allah be upon him) said: “The imam has only been appointed to be followed, so do not differ from him… And when he prostrates, then prostrate.” End quote.
Based on that, the one who is praying behind the imam in the example mentioned must follow the imam in doing the prostration of forgetfulness.
And Allah knows best.