Question:
I am working on a problem where I need to make every value in an integer array nums
unique with the minimum number of moves. In each move, I can pick an index i
(where 0 <= i < nums.length
) and increment nums[i]
by 1.
I need to return the minimum number of moves required to achieve this.
Here are a couple of examples:
Example 1:
-
Input:
nums = [1, 2, 2]
-
Output:
1
-
Explanation: After 1 move, the array could be
[1, 2, 3]
.
Example 2:
-
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 that with 5 or fewer moves, it is impossible for the array to have all unique values.
Issue:
When I sort the array and find duplicate elements using the ==
operator, the code does not provide the required results. However, when I change the comparison to <=
, it passes all test cases. Here is the code snippet:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> nums={3,2,1,2,1,7}; //The given testcase
int minIncrements = 0;
sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) { //Equality operator produce incorrect
//if (nums[i] <= nums[i - 1]) { // This works correctly
int incrementNeeded = nums[i - 1] - nums[i] + 1;
nums[i] += incrementNeeded;
minIncrements += incrementNeeded;
}
}
cout<<minIncrements; //Expected to be 6 but return 2
return 0;
}
Question:
I am trying to solve a problem where I need to make every value in an integer array nums
unique with the minimum number of moves. Each move increments any chosen element by 1.
When I use the condition if (nums[i] <= nums[i - 1])
in my code, it works correctly. However, when I change it to if (nums[i] == nums[i - 1])
, the output is incorrect. I thought both should check for duplicate elements.
Could someone explain why using ==
does not work correctly, but using <=
does?