<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 {
private:
    int dist(map<int,vector<int>>& mn, map<int,vector<int>>::iterator it, map<int,vector<int>>& mx){
        int i1 = it->first;
        vector<int>& a1 = it->second;

        auto jt = mx.end(); jt--;
        int i2 = jt->first;
        vector<int>& a2 = jt->second;

        int d = 0;
        if(a1[0] == a2[0] && a1.size() == 1 && a2.size()==1){
            jt--;
            i2 = jt->first;
            d = i1-i2;
        } else {
            d = i1-i2;
        }

        if (d<0) d=-d;
        return d;

    }
public:
    int maxDistance(vector<vector<int>>& arrays) {
        map<int,vector<int>> mn,mx;
        for(int i = 0; i < arrays.size(); ++i){
            vector<int>& v = arrays[i];

            if(mn.contains(v[0])){
                mn[v[0]].push_back(i);
            } else {
                mn.insert({v[0],{i}});
            }
            if (mx.contains(v[v.size()-1])){
                mx[v[v.size()-1]].push_back(i);
            } else {
                mx.insert({v[v.size()-1],{i}});
            }
        }

        auto it = mn.begin();
        int d1 = dist(mn, it,mx);
        int d2 = 0;
        if (mn.size() > 1){
            it++;
            d2 = dist(mn, it,mx);
        }
        
        return max(d1,d2);
    }
};
116978