HanchengZhao / algorithm-notes

0 stars 0 forks source link

624. Maximum Distance in Arrays #9

Open YeWang0 opened 7 years ago

YeWang0 commented 7 years ago

Given m arrays, and each array is sorted in ascending order. Now 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 a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 1: Input: [[1,2,3], [4,5], [1,2,3]] Output: 4 Explanation: 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. Note: Each given array will have at least 1 number. There will be at least two non-empty arrays. The total number of the integers in all the m arrays will be in the range of [2, 10000]. The integers in the m arrays will be in the range of [-10000, 10000].

YeWang0 commented 7 years ago

A good solution which stores only one MAX and MIN

public class Solution { public int maxDistance(int[][] arrays) { int result = Integer.MIN_VALUE; int max = arrays[0][arrays[0].length - 1]; int min = arrays[0][0];

    for (int i = 1; i < arrays.length; i++) {
        result = Math.max(result, Math.abs(arrays[i][0] - max));
        result = Math.max(result, Math.abs(arrays[i][arrays[i].length - 1] - min));
        max = Math.max(max, arrays[i][arrays[i].length - 1]);
        min = Math.min(min, arrays[i][0]);
    }

    return result;
}

}

YeWang0 commented 7 years ago

how to think in a different way

HanchengZhao commented 7 years ago

Here is my solution during the contest:

class Solution(object):
    def maxDistance(self, arrays):
        small = []
        big = []
        for index, arr in enumerate(arrays):
            small.append([arr[0],index])
            big.append([arr[-1],index])
        small = sorted(small)
        big = sorted(big)
        if small[0][1] != big[-1][1]:
            return big[-1][0] - small[0][0]
        else:
            return max(big[-2][0] - small[0][0], big[-1][0] - small[1][0])

I saved the array index to examine whether the biggest and the smallest came from the same array.