Given an array of integers nums, a move consists of choosing any nums[i]
, and incrementing it by 1
.
Return the least number of moves to make every value in nums
unique.
Input: nums = [1,2,2] Output: 1 Explanation: After 1 move, the array could be [1, 2, 3].
Input: nums = [3,2,1,2,1,7] Output: 6 Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
0 <= nums.length <= 40000
0 <= nums[i] < 40000
# @param {Integer[]} nums
# @return {Integer}
def min_increment_for_unique(nums)
nums.sort!
ret = 0
(1...nums.size).each do |i|
ret += [nums[i], nums[i - 1] + 1].max - nums[i]
nums[i] = [nums[i], nums[i - 1] + 1].max
end
ret
end
impl Solution {
pub fn min_increment_for_unique(mut nums: Vec<i32>) -> i32 {
nums.sort_unstable();
let mut ret = 0;
for i in 1..nums.len() {
ret += nums[i].max(nums[i - 1] + 1) - nums[i];
nums[i] = nums[i].max(nums[i - 1] + 1);
}
ret
}
}