Greedy Algorithms8 sections · 316 units
Open in Course

Make Unique - Greedy Approach

Sort and fix

Sort the array. Scan left to right. Each element must be at least one more than the previous.

If arr[i]arr[i1]arr[i] \leq arr[i-1], increment arr[i]arr[i] to arr[i1]+1arr[i-1] + 1. The cost is the difference.

Here's greedy because you fix each violation with the minimum possible increment.

You cannot do better: the element must be unique and at least as large as it was. Why this is optimal: each element must be at least its original value.

If arr[i]arr[i1]arr[i] \leq arr[i-1], the smallest valid value is arr[i1]+1arr[i-1] + 1. Choosing anything larger would waste increments. The greedy choice minimizes cost at each step.