Nearly extremal Cohen–Macaulay and Gorenstein algebras