For the $n-1$ processes that use the first code, they enter their critical section only after acquiring the semaphore. But the last process $P_n$ is entering its critical section but instead of waiting for the semaphore, it signals it.
Let's suppose $P_1$ enters the critical section first. So, it sets the semaphore $S$ to 0, which was initialized to 1. (remember it's a binary semaphore).
Now, while $P_1$ is executing in its C.S., let's see what happens if $P_n$ also goes to its C.S. Before entering, it will set the semaphore $S$ to 1 by signal(S)
. And then goes to its C.S.
Now another process, say $P_2$ tries to enter its C.S. and it gets it because $S$ is 1. It again sets $S$ to 0 and goes to C.S.
Currently, we have 3 processes in C.S.($P_1, P_2, P_n$).
Now, if $P_n$ leaves its C.S., it will again signal(S), and sets $S$ to 1. Another process, say $P_3$ can now enter the C.S.
Then again $P_n$ goes to its C.S., which allows another process to go to C.S.
Continuing this way, in the worst case, all the n processes can be in their critical section simultaneously.