1509. Minimum Difference Between Largest and Smallest Value in Three Moves #279
-
Topics: You are given an integer array In one move, you can choose one element of Return the minimum difference between the largest and smallest value of Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
In this problem, we are given an integer array Key Points
Approach
Plan
Let's implement this solution in PHP: 1509. Minimum Difference Between Largest and Smallest Value in Three Moves <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minDifference($nums) {
$n = count($nums);
// If the array has 4 or fewer elements, the difference is zero because we can remove all but one element.
if ($n <= 4) {
return 0;
}
// Sort the array to facilitate the calculation of differences after removals.
sort($nums);
// We consider removing 0, 1, 2, or 3 elements from the start or the end.
// Calculate the differences:
// 1. Remove 3 from start: nums[n-1] - nums[3]
// 2. Remove 2 from start, 1 from end: nums[n-2] - nums[2]
// 3. Remove 1 from start, 2 from end: nums[n-3] - nums[1]
// 4. Remove 3 from end: nums[n-4] - nums[0]
$differences = [
$nums[$n - 1] - $nums[3],
$nums[$n - 2] - $nums[2],
$nums[$n - 3] - $nums[1],
$nums[$n - 4] - $nums[0]
];
// Return the minimum difference.
return min($differences);
}
// Example usage:
$nums1 = [5,3,2,4];
$nums2 = [1,5,0,10,14];
$nums3 = [3,100,20];
echo minDifference($nums1) . "\n"; // Output: 0
echo minDifference($nums2) . "\n"; // Output: 1
echo minDifference($nums3) . "\n"; // Output: 0
?> Explanation:We perform the following steps to solve the problem:
Example WalkthroughExample 1:
Example 2:
Example 3:
Time Complexity
Output for ExampleExample 1:
Example 2:
Example 3:
This approach efficiently computes the minimum difference between the largest and smallest values after at most three moves by leveraging sorting and considering only four possible changes to the array. It handles edge cases and provides the result in |
Beta Was this translation helpful? Give feedback.
In this problem, we are given an integer array
nums
. The goal is to find the minimum difference between the largest and smallest values of the array after performing at most three moves. In each move, we can change one element of the array to any value. This problem focuses on minimizing the difference between the maximum and minimum values by making strategic modifications.Key Points
At most three moves: We are allowed to make three changes to the array, which means we can either remove or alter three elements to minimize the difference between the largest and smallest values.
Optimization: Instead of brute-forcing all possible combinations of values to change, we can simplify the t…