<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:
    def maxDistance(self, arr: List[List[int]]) -> int:
        Pm = [arr[0][0]]
        Sm = [float('inf')] * len(arr)
        Sm[-1] = arr[-1][0]
        PM = [arr[0][-1]]
        SM = [0] * len(arr)
        SM[-1] = arr[-1][-1]
        for i in arr[1:]:
            Pm += [min(Pm[-1],i[0])]
            PM += [max(PM[-1],i[-1])]
        for j in range(len(arr)-2,-1,-1):
            i = arr[j]
            Sm[j] = min(Sm[j+1],i[0])
            SM[j] = max(SM[j+1],i[-1])
        ans = -float('inf')
        for i in range(len(arr)):
            mini = arr[i][0]
            maxi = arr[i][-1]
            if i:
                ans = max(ans,(mini-Pm[i-1]))
                ans = max(ans,(mini-PM[i-1]))
                ans = max(ans,(maxi-Pm[i-1]))
                ans = max(ans,(maxi-PM[i-1]))
                ans = max(ans,(Pm[i-1]-mini))
                ans = max(ans,(PM[i-1]-mini))
                ans = max(ans,(Pm[i-1]-maxi))
                ans = max(ans,(PM[i-1]-maxi))
            if i!=len(arr)-1:
                ans = max(ans,(Sm[i+1]-mini))
                ans = max(ans,(SM[i+1]-mini))
                ans = max(ans,(Sm[i+1]-maxi))
                ans = max(ans,(SM[i+1]-maxi))
                ans = max(ans,(mini-Sm[i+1]))
                ans = max(ans,(mini-SM[i+1]))
                ans = max(ans,(maxi-Sm[i+1]))
                ans = max(ans,(maxi-SM[i+1]))
        return ans
        


        

38628