624. Maximum Distance in Arrays #331
-
Topics: You are given 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 Return the maximum distance. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We need to calculate the maximum possible distance between two integers, each picked from different arrays. The key observation is that the maximum distance will most likely be between the minimum value of one array and the maximum value of another array. To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 624. Maximum Distance in Arrays <?php
function maxDistance($arrays) {
$min_value = $arrays[0][0];
$max_value = end($arrays[0]);
$max_distance = 0;
for ($i = 1; $i < count($arrays); $i++) {
$current_min = $arrays[$i][0];
$current_max = end($arrays[$i]);
// Calculate distance with the current min and global max
$max_distance = max($max_distance, abs($current_max - $min_value));
// Calculate distance with the current max and global min
$max_distance = max($max_distance, abs($max_value - $current_min));
// Update global min and max
$min_value = min($min_value, $current_min);
$max_value = max($max_value, $current_max);
}
return $max_distance;
}
// Example usage:
$arrays1 = [[1,2,3],[4,5],[1,2,3]];
echo maxDistance($arrays1); // Output: 4
$arrays2 = [[1],[1]];
echo maxDistance($arrays2); // Output: 0
?> Explanation:
This solution runs in O(m) time, where m is the number of arrays, making it efficient given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to calculate the maximum possible distance between two integers, each picked from different arrays. The key observation is that the maximum distance will most likely be between the minimum value of one array and the maximum value of another array.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 624. Maximum Distance in Arrays