Editorial
First consider the case . If , construct a matrix for and then transpose it. Transposition swaps rows and columns, so it swaps and and changes the sign of their difference.
Every row contains distinct positive integers, so its maximum is at least . Hence . Also, the maxima of the rows are distinct, so their minimum is at most . Therefore
The same argument gives
Thus a necessary condition is
Now suppose , and let .
Set
For every , set
Thus the largest values are placed on the diagonal.
If , also set
Fill every still-empty cell from top-left to bottom-right with the smallest positive integer that has not been used yet.
When , we have . Hence the other cells of the first row receive values smaller than , so the maximum of the first row is . For every later row, its diagonal entry is its maximum. Therefore
Column contains , while each other column contains one of . Hence
Thus .
When , we have , and the minimum row maximum and the minimum column maximum are both , so the construction is also valid.
Therefore a solution exists exactly when . Filling the matrix takes time per case, or over the entire input.
Solution written by GPT5.6