<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p>

<p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p>

<p>Return <em>the maximum distance</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arrays = [[1],[1]]
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == arrays.length</code></li>
	<li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= arrays[i].length &lt;= 500</code></li>
	<li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li>
	<li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li>
	<li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li>
</ul>

class Solution {
    int INF = 1e9;
public:
    int maxDistance(vector<vector<int>>& arrays) {
        int n = arrays.size();

        vector<pair<int,int>> minMax(n);
        for(int i = 0; i < n; ++i){
            int currMin = *min_element(arrays[i].begin(), arrays[i].end());
            int currMax = *max_element(arrays[i].begin(), arrays[i].end());
            minMax[i] = {currMin, currMax};
        }

        vector<array<int,4>> v(n, {INF, -INF, INF, -INF});

        // {prefixMin, prefixMax, suffixMin, suffixMax}

        // setting prefix min and max
        for(int i = 1; i < n; ++i){
            auto [prevMin, prevMax] = minMax[i-1];
            v[i][0] = min(v[i-1][0], prevMin);
            v[i][1] = max(v[i-1][1], prevMax);
        }

        // setting suffix min and max
        for(int i = n-2; i >= 0; --i){
            auto [nextMin, nextMax] = minMax[i+1];
            v[i][2] = min(v[i+1][2], nextMin);
            v[i][3] = max(v[i+1][3], nextMax);
        }

        // set answer
        int ans = 0;
        for(int i = 0; i < n; ++i){
            auto [currMin, currMax] = minMax[i];
            for(int j = 0; j < 4; ++j){
                if(abs(v[i][j]) < INF){
                    ans = max(ans, abs(currMin - v[i][j]));
                    ans = max(ans, abs(currMax - v[i][j]));
                }
            }
        }

        return ans;
    }
};
114184