diff options
-rw-r--r-- | max_distance_arr.c | 29 | ||||
-rw-r--r-- | max_distance_arr.py | 27 |
2 files changed, 56 insertions, 0 deletions
diff --git a/max_distance_arr.c b/max_distance_arr.c new file mode 100644 index 0000000..40cc5a2 --- /dev/null +++ b/max_distance_arr.c @@ -0,0 +1,29 @@ +// 624. Maximum Distance in Arrays +#include "leetcode.h" + +/* + * you are given 'm' arrays where each array is sorted in ascending order. you + * can pick up two integers from two different arrays (each array picks one) and + * calculate the distance. we define the distance between two integer 'a' and + * 'b' to be their absolute idfferent '|a - b|'. return the maximum distance + */ + +int maxDistance(int **arrays, int arraysSize, int *arraysColSize) { + if (!arraysSize) + return -1; + int min = arrays[0][0], max = arrays[0][arraysColSize[0] - 1], ans = 0; + for (int i = 1; i < arraysSize; i++) { + int curr = fmax(arrays[i][arraysColSize[i] - 1] - min, max - arrays[i][0]); + ans = fmax(max, curr); + min = fmin(min, arrays[i][0]); + max = fmax(max, arrays[i][arraysColSize[i] - 1]); + } + return ans; +} + +int main() { + int a1[][3] = {{1, 2, 3}, {4, 5}, {1, 2, 3}}, a2[][2] = {{1}, {1}}; + int acs1[] = {3, 3, 2}, acs2[] = {1, 1}; + printf("%d\n", maxDistance((int **)a1, ARRAY_SIZE(a1), acs1)); // expect: 4 + printf("%d\n", maxDistance((int **)a2, ARRAY_SIZE(a2), acs2)); // expect: 0 +} diff --git a/max_distance_arr.py b/max_distance_arr.py new file mode 100644 index 0000000..ab0b9de --- /dev/null +++ b/max_distance_arr.py @@ -0,0 +1,27 @@ +# 624. Maximum Distance in Arrays + +""" +you are given 'm' arrays where each array is sorted in ascending order. you +can pick up two integers from two different arrays (each array picks one) and +calculate the distance. we define the distance between two integer 'a' and +'b' to be their absolute idfferent '|a - b|'. return the maximum distance +""" + + +class Solution(object): + def maxDistance(self, arrays): + """ + :type arrays: List[List[int]] + :rtype: int + """ + ans, curr_min, curr_max = 0, 10000, -10000 + for i in arrays: + ans = max(ans, max(i[-1] - curr_min, curr_max - i[0])) + curr_min, curr_max = min(curr_min, i[0]), max(curr_max, i[-1]) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxDistance(arrays=[[1, 2, 3], [4, 5], [1, 2, 3]])) + print(obj.maxDistance(arrays=[[1], [1]])) |