Partition an H by W grid into two connected regions whose row and column slices are contiguous, minimizing the larger altitude range within either region.
Hard9Binary searchGreedyImplementationArrayNo attempts yetTime limit4sMemory limit256 MBThe Kingdom of JOIOI is a rectangular grid of H×W cells. To make its administrative institutions more efficient, the kingdom will divide the country into two regions called "JOI" and "IOI".
The kingdom does not want a complicated division, so the division must satisfy all of the following conditions:
Each cell has an integer called its altitude. After the division, the kingdom expects travel within each region to become active. However, traveling between cells with a large altitude difference is hard. Therefore, the kingdom wants to minimize the maximum altitude difference between cells of the same region. In other words, it wants to minimize the larger of these two values:
Given the altitudes of the cells of the Kingdom of JOIOI, write a program that computes the minimum possible value of the larger of these two differences over all valid divisions.
The first line contains two integers H and W separated by a space. The Kingdom of JOIOI is a grid of H×W cells.
The i-th of the following H lines (1≤i≤H) contains W integers Ai,1,Ai,2,…,Ai,W separated by spaces. The cell in the i-th row from the top and the j-th column from the left (1≤j≤W) has altitude Ai,j.
Print one line: the minimum, over all valid divisions, of the larger of the altitude difference (maximum minus minimum) in the JOI region and the altitude difference in the IOI region.