5. Given a square table of size $2023 \times 2023$. Each of its cells is colored in one of $n$ colors. It is known that for any six cells of the same color located in the same row, there are no cells of the same color above the leftmost of them and below the rightmost of them. What is the smallest $n$ for which this is possible?
Answer: 338.

Solution. Consider some specific color (say, blue). In each row, mark the five leftmost blue cells with a cross, and the rest with a zero (if there are fewer than six blue cells in the row, mark all cells with a cross). Note that in any column, there is no more than one blue cell with a zero (otherwise, for the topmost one, the condition of the problem is violated). Therefore, there are no more than 2023 blue cells with a zero. In addition, the number of blue cells with a cross does not exceed $5 \cdot 2023$. Thus, the total number of blue cells does not exceed $2023 + 5 \cdot 2023 = 6 \cdot 2023$. These arguments are valid for any color. Therefore, the total number of colors is no less than

$$
\frac{2023^{2}}{6 \cdot 2023} = \frac{2023}{6} = 337 \frac{1}{6}
$$

Thus, $n \geqslant 338$.

We will show that $n=338$ is achievable. Sequentially number all diagonals from top to bottom, running from southwest to northeast, with numbers from 1 to 4045. Paint the first six diagonals in the first color, the next six in the second color, and so on in a cycle (so after the 338th color, the first color will follow again). We will check that this coloring satisfies the condition of the problem. Note that no color is used more than twice, since $338 \cdot 6 \cdot 2 = 4056 > 4045$. Let the $k$-th color appear twice. In the first block, the rightmost cell of this color will be in the column with number $6k$. In the second block, the leftmost cell of this color is in the column with number

$$
6(338+k-1)+1-2022 = 6k+1
$$

Thus, cells of the same color from different blocks cannot be in the same column.