The task is:
Given an array of integers, return the minimum required increment to make each element unique.
Sample Input 1: [3, 4, 2, 2, 6]
Sample Output 1: 3 (One of the 2s should be incremented to 5)
Sample Input 2: [3, 4, 5]
Sample Output 2: 0 (There is no duplicate)
My code works by shifting all numbers even if there is only one duplicate in a whole array. I guess this could be written more efficiently (e.g., in each duplicate, looking at the minimum number that does not exist in the array and shifting one of the duplicates to that number), but I couldn't manage it.
def getMinimumCoins(arr):
sumBefore = sum(arr)
arr.sort()
previous = arr[0]
for i in range(1, len(arr)):
if arr[i] <= previous:
arr[i] = previous + 1
previous = arr[i]
return sum(arr) - sumBefore
Besides, in the way I proposed above, decremental operations also could be possible. I mean, in my code, if the input is [3,3,3], the resulting array would be [3,4,5] with total increment equals 3. However, in the new algorithm, it could be possible to obtain a resulting array of [1,2,3] with a total decrement equals to -3.
arr.sort()
" does not run in linear time, so your code is not linear. \$\endgroup\$[3, 3, 6]
? You could get there by one increment (arr[1] += 1 -> 4
) and one decrement (arr[2] -= 1 -> 5
). Is the expected output0
, because one increment and one decrement "cancel each other out"? Or2
(1 increment of value1
, plus 1 decrement of value1
)? Or perhaps(1, 1)
, indicating the sum of all required increments is1
, and the sum of all required decrements is also1
? \$\endgroup\$