945. Minimum Increment to Make Array Unique #198
-
You are given an integer array Return the minimum number of moves to make every value in The test cases are generated so that the answer fits in a 32-bit integer. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to make every number in a given integer array unique. We can increment any number in the array in one move, and the goal is to minimize the total number of moves required to ensure that each element is distinct. Key Points:
Approach:The strategy involves sorting the array and then iterating over it, ensuring each number is greater than the last (if a number repeats). If a number is smaller than or equal to the previous number (or the minimum available number), we increment it and count the moves.
Plan:
Let's implement this solution in PHP: 945. Minimum Increment to Make Array Unique <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minIncrementForUnique($nums) {
$ans = 0;
$minAvailable = 0;
sort($nums);
foreach ($nums as $num) {
$ans += max($minAvailable - $num, 0);
$minAvailable = max($minAvailable, $num) + 1;
}
return $ans;
}
// Example usage:
$nums1 = [1,2,2];
$nums2 = [3,2,1,2,1,7];
echo minIncrementForUnique($nums1) . "\n"; // Output: 1
echo minIncrementForUnique($nums2) . "\n"; // Output: 6
?> Explanation:
Example Walkthrough:Example 1:
Example 2:
Time Complexity:
Output for Example:Example 1:
Example 2:
The approach efficiently solves the problem by sorting the array and using a greedy strategy to make each element unique. By processing the elements in ascending order, we ensure that we minimize the number of moves required to resolve duplicates. The solution has a time complexity of O(n log n), making it feasible even for large inputs (up to 105 elements). |
Beta Was this translation helpful? Give feedback.
The problem asks us to make every number in a given integer array unique. We can increment any number in the array in one move, and the goal is to minimize the total number of moves required to ensure that each element is distinct.
Key Points:
Approach:
The strategy involves sorting the array and then iterating over it, ensuring each number is greater than the last (if a number repeats). If a number is smaller than or equal to the previous number (or the minimum available number),…